/*
 * ******************************************************************************
 *  jquery.mb.components
 *  file: jquery.browser.js
 *
 *  Copyright (c) 2001-2013. Matteo Bicocchi (Pupunzi);
 *  Open lab srl, Firenze - Italy
 *  email: matteo@open-lab.com
 *  site: 	http://pupunzi.com
 *  blog:	http://pupunzi.open-lab.com
 * 	http://open-lab.com
 *
 *  Licences: MIT, GPL
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 *  last modified: 16/01/13 20.38
 *  *****************************************************************************
 */

/*******************************************************************************
 *
 * jquery.browser
 * Author: pupunzi
 * Creation date: 16/01/13
 *
 ******************************************************************************/
/*Browser detection patch*/

(function($){

	var jQversion = jQuery.fn.jquery.split(".");
	if(jQversion[1]<8)
		return;

	jQuery.browser = {};
	jQuery.browser.mozilla = false;
	jQuery.browser.webkit = false;
	jQuery.browser.opera = false;
	jQuery.browser.msie = false;

	var nAgt = navigator.userAgent;
	jQuery.browser.name  = navigator.appName;
	jQuery.browser.fullVersion  = ''+parseFloat(navigator.appVersion);
	jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
	var nameOffset,verOffset,ix;

//	In Opera, the true version is after "Opera" or after "Version"
	if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
		jQuery.browser.opera = true;
		jQuery.browser.name = "Opera";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+6);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In MSIE, the true version is after "MSIE" in userAgent
	else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
		jQuery.browser.msie = true;
		jQuery.browser.name = "Microsoft Internet Explorer";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+5);
	}
//	In Chrome, the true version is after "Chrome"
	else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
		jQuery.browser.webkit = true;
		jQuery.browser.name = "Chrome";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
	}
//	In Safari, the true version is after "Safari" or after "Version"
	else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
		jQuery.browser.webkit = true;
		jQuery.browser.name = "Safari";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+7);
		if ((verOffset=nAgt.indexOf("Version"))!=-1)
			jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In Firefox, the true version is after "Firefox"
	else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
		jQuery.browser.mozilla = true;
		jQuery.browser.name = "Firefox";
		jQuery.browser.fullVersion = nAgt.substring(verOffset+8);
	}
//	In most other browsers, "name/version" is at the end of userAgent
	else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
			(verOffset=nAgt.lastIndexOf('/')) )
	{
		jQuery.browser.name = nAgt.substring(nameOffset,verOffset);
		jQuery.browser.fullVersion = nAgt.substring(verOffset+1);
		if (jQuery.browser.name.toLowerCase()==jQuery.browser.name.toUpperCase()) {
			jQuery.browser.name = navigator.appName;
		}
	}
//	trim the fullVersion string at semicolon/space if present
	if ((ix=jQuery.browser.fullVersion.indexOf(";"))!=-1)
		jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);
	if ((ix=jQuery.browser.fullVersion.indexOf(" "))!=-1)
		jQuery.browser.fullVersion=jQuery.browser.fullVersion.substring(0,ix);

	jQuery.browser.majorVersion = parseInt(''+jQuery.browser.fullVersion,10);
	if (isNaN(jQuery.browser.majorVersion)) {
		jQuery.browser.fullVersion  = ''+parseFloat(navigator.appVersion);
		jQuery.browser.majorVersion = parseInt(navigator.appVersion,10);
	}
	jQuery.browser.version = jQuery.browser.majorVersion;
})(jQuery)
/*
document.write(''
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br><br><br>'
 +'jQuery.browser.name  = '+jQuery.browser.name+'<br>'
 +'jQuery.browser.fullVersion  = '+jQuery.browser.fullVersion+'<br>'
 +'jQuery.browser.version = '+jQuery.browser.version+'<br><br><br>'
 +'jQuery.browser.msie = '+jQuery.browser.msie+'<br>'
 +'jQuery.browser.mozilla = '+jQuery.browser.mozilla+'<br>'
 +'jQuery.browser.opera = '+jQuery.browser.opera+'<br>'
 +'jQuery.browser.webkit = '+jQuery.browser.webkit+'<br>'
)
 */

$(document).ready(function(){

	$('#googleCalendarSyncSchedule').hide();
	$('#googleCalendarSyncExams').hide();
	$('#saveSchedule').hide();
	$('#loadSchedule').hide();

	/*variable to hold the current "request" which was earlier*/
	var requestAjax;
	var syllabusRequestAjax;

	//Global variables (accessed by all screens)
	window.bidit_globals =
	{
			//Globals For google calendar
			g_acsess : false,
			g_url_to_access : '',


			//current logged in user information
			g_userID: '',
			g_facebookUserID: '',
			g_userEmail: '',
			g_userNickName: '',
			g_currUniversity: 'TAU',
			g_loginUrl: '',

			// List of faculties and thier departments of the current semester
			g_facultiesAndDeparts: [],

			g_optimizeData: [{"maxDays":6,"sundayOff":false,"mondayOff":false,
				"tuesdayOff":false,"wednesdayOff":false,"thursdayOff":false
				,"fridayOff":false,"minHour":"08:00","maxHour":"22:00",
				"examsGap":0,"mustHaveCourses":[]},
				{"maxDays":6,"sundayOff":false,"mondayOff":false,
					"tuesdayOff":false,"wednesdayOff":false,"thursdayOff":false
					,"fridayOff":false,"minHour":"08:00","maxHour":"22:00",
					"examsGap":0,"mustHaveCourses":[]}],

					g_helpOptimize: false,
					g_ajaxMiddleShown: true,
					g_ajaxStopMessage: "",
					g_showWelcomePage: true,
					g_userConnected: false,
					g_isFirstTimeOnCatalog: true,
					g_currHebrewYear: 'תשע"ו',
					g_metaDatesDS: {
"metaDates":['10/18/2015','12/13/2015','01/17/2016',
'03/24/2016','02/25/2016','04/15/2016','05/01/2016',
'05/11/2016','05/12/2016','06/12/2016','05/26/2016',
'06/10/2016','07/03/2016','08/19/2016','10/30/2016'],

"metaTypes":[['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],
['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta']],

"metaMoeds":[['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],
['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta'],['meta']],

"metaColors":[['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],
['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta'],['Meta']],

"metaNames":[['היום הראשון ללימודים'],['חופשת חנוכה'],['היום האחרון לסמסטר הראשון'],
['פורים'],['היום הראשון לסמסטר השני'],
['יום אחרון לפני חופשת הפסח וימי השלמות'],['היום הראשון ללימודים לאחר חופשת פסח'],
['יום הזיכרון לחללי מערכות ישראל'],['יום העצמאות'],
['חופשת שבועות'],['יום הסטודנט'],['היום האחרון לסמסטר השני'],
['היום הראשון לעונת לימודי הקיץ'],['היום האחרון לעונת לימודי הקיץ'],
['היום הראשון ללימודים בשנת תשע"ז 2016/17']],

"metaCrashes":[false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]},
	
					g_currSemester: 0,
					g_currCourseProfile : '-1',
					g_currChosenDepart: 'NOT_CHOSEN',
					g_currChosenInfoBtnDepart: 'NOT_CHOSEN',
					g_currChosenDepartName: '',
					g_currChosenFacultyName: '',
					g_currChosenFacultyNum: 'NOT_CHOSEN',
					g_currChosenDayNum: -1,
					g_printOnlyCurrSem: false,
					g_viaLcalStorage: false,
					g_printBool: false,

					/*all exams: each element in this array is an array with 9 elements, each place: 0-date(Date) ,1-name("Logic") ,2-color("#ffff95") ,3-number("03682170" ,4-moed("א") ,5-type("בחינה סופית") ,6-semester(0) ,7-exam begin hour("14:00") ,8-exam end hour("---") */
					g_examObj: [], 
					g_examObj2: [],

					g_firstExamDate: 'today',
					g_currCourseInfo: [],
					g_currCourseUploaded: false,
					g_toSaveSelection: false,
					g_isProfileOpenedFromMain: true,
					g_newChosenCoursesArr: [], // new courses that were chosen in the course catalog
					g_chosenCoursesArr: [], // total courses the user chose (presented on main screen accordion)
					g_chosenCourses_A: [],
					g_chosenCourses_B: [],

					g_currSpanSub: '',

					//Saves the users schedule for 3 semesters
					g_scheduleArr_A: [], 
					g_scheduleArr_B: [],
					g_schedulesArr: [],
					g_totalHoursArr: [],
					g_totalHours_A: '0',
					g_totalHours_B: '0',
					g_totalZchutHoursArr: [],
					g_totalZchutHours_A: 0.0,
					g_totalZchutHours_B: 0.0,
					/*variable to hold to last width of the window for print*/
					g_printRes: $('html').width(),

					// Saves all the information for courses accordions (from server)
					g_allSemestersAccordions: [],
					g_jsonCoursesAccordionInfoA: [], //Saves the accordion chosen courses info for 2 semesters
					g_jsonCoursesAccordionInfoB: [],

					// Info about courses display on schedule
					g_coursesDisplaySettings: [],

					g_coursesDisplaySettings_A: {},
					g_coursesDisplaySettings_B: {},

					g_colorsStock: [],
					g_COLORS_FIRST: ["#26FF56","#26FFE7","#FFFF95","#FF6A4C","#6CAFF2","#E2A9F3"],
					g_COLORS_PERMANENT: ["#FF6FAE","#FA8989","#70A46F","#B88A3E","#B9868E","#DFFF26","#FFC226","#A9A17D","#D363F5"],
					g_COLORS_EXTRA: ["#0489B1","#F78181","#04B404","#D8CEF6","#81DAF5","#CEF6CE","#8A0886","#BDBDBD","#868A08","#F5A9BC",
					                 "#2E64FE","#CED8F6","#FF0040","#81F79F","#9F81F7","#CEF6F5","#DF0101","#4FE717","#F79F81","#FBEFEF","#F7819F","#00FFBF","#D0A9F5","#F2F5A9","#C8E9F6","#BFFF00","#F6229A","#DBA901","#DF01D7","#BE99AE","#15AC84","#F2A376","#F4F40A","#AC10F4","#1099F4","#10F4F4","#C9DAB2","#F43575","#DBA4F9","#25EB17","#B64E09","#949EC9","#31D8CA","#F2EB1A","#AF18A5"],
					                 g_scheduleColors: [],

					                 g_jsonOptimizer: [],

					                 g_contactFormBool: {"nameContact":false,"emailContact":false,"subjectContact":false,"freeText":false},

					                 g_supportToMail: 'bidit.contact@gmail.com',
					                 g_supportFromMail: 'bidit.contact@gmail.com',
					                 g_supportFromMailTxt: '',
					                 g_supportFromName: '',
					                 g_supportMailBody: '',
					                 g_supportMailSubject: ''

	};



	/* Initializing login process*/
	getLoginUrl();

	//getFacultiesAndDepartsFromAjax();

	window.bidit_globals.g_allSemestersAccordions.push(window.bidit_globals.g_jsonCoursesAccordionInfoA);
	window.bidit_globals.g_allSemestersAccordions.push(window.bidit_globals.g_jsonCoursesAccordionInfoB);

	window.bidit_globals.g_schedulesArr.push(window.bidit_globals.g_scheduleArr_A);
	window.bidit_globals.g_schedulesArr.push(window.bidit_globals.g_scheduleArr_B);

	window.bidit_globals.g_totalHoursArr.push(window.bidit_globals.g_totalHours_A);
	window.bidit_globals.g_totalHoursArr.push(window.bidit_globals.g_totalHours_B);

	window.bidit_globals.g_totalZchutHoursArr.push(window.bidit_globals.g_totalZchutHours_A);
	window.bidit_globals.g_totalZchutHoursArr.push(window.bidit_globals.g_totalZchutHours_B);

	window.bidit_globals.g_coursesDisplaySettings.push(window.bidit_globals.g_coursesDisplaySettings_A);
	window.bidit_globals.g_coursesDisplaySettings.push(window.bidit_globals.g_coursesDisplaySettings_B);

	window.bidit_globals.g_chosenCoursesArr.push(window.bidit_globals.g_chosenCourses_A);
	window.bidit_globals.g_chosenCoursesArr.push(window.bidit_globals.g_chosenCourses_B);

	//Initializing cookies every day
	clearOldCookies();

	/*shuffle the permanent colors array, and then adding the extra colors array, finaly reversing the order for the algoritm to work*/
	copyColorsArray();

	/*reset optimizer*/
	/*semester Alef reset*/
	resetOptimizeDate(0);
	/*semester Bet reset*/
	resetOptimizeDate(1);


	// Checks if there is suppurt for localstorage
	checkForStoredData();

	/*check if need to switch to semester B*/
	checkIfSwitchNeeded();

	/*update exams and calendar*/
	updateExamsAndCalendar();

	/*clear and foucs on course search*/
	clearAndFocusCourseSearch();


	/**/
	if((jQuery.browser.name.toLowerCase() == 'safari') ||
			(navigator.userAgent.toLowerCase().indexOf('Safari') > -1)){
		$('#fbLikeLIGapped').css('margin-left','132px','!important');
	}

	//The function checks if this is the first time the user entered today to the site, if it is - it deletes the old cookies
	//This happens to ensure the cookies will be up to date with the DB information.
	function clearOldCookies(){
		var currDate = new Date();
		var currDay = currDate.getDay();
		var currMonth = currDate.getMonth();
		var currYear = currDate.getFullYear();

		var strCurrDate = currDay + "-" + currMonth + "-" + currYear;

		if(typeof(Storage)!=="undefined")
		{

			if(localStorage.biditLastUpdate == null){
				//Update cookie to be current date
				localStorage.biditLastUpdate = strCurrDate;

				//Initializing cookies value to be 'none'
				localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
				localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
				localStorage.setItem('catalog_modal_details_semestera','-100');
				localStorage.setItem('catalog_modal_details_semesterb','-100');

			}
			else{
				if(localStorage.biditLastUpdate == strCurrDate){
					//do nothing
				}
				else{
					//Update cookie to be current date
					localStorage.biditLastUpdate = strCurrDate;

					//Initializing cookies value to be 'none'
					localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
					localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
					localStorage.setItem('catalog_modal_details_semestera','-100');
					localStorage.setItem('catalog_modal_details_semesterb','-100');
				}
			}
		}
		else
		{
			showAlert('הדפדפן שלך אינו תומך בשימוש באתר זה, עליך לעדכן אותו', 'error');
		}

	}

	// The function checks of there is a local schedule data saved in the user's computer
	function checkForStoredData(){
		initAutoComplete();
		if(typeof(Storage)!=="undefined")
		{
			if(localStorage.inWebsiteForTheFirstTime == '1'){

				showStoredScheduleData();
			}
			else{
				localStorage.inWebsiteForTheFirstTime = '1';
				localStorage.isDataSaved_A = '1';
				localStorage.isDataSaved_B = '1';
				localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
				localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
			}
			//initAutoComplete();
		}
		else
		{
			showAlert('הדפדפן שלך אינו תומך בשימוש באתר זה, עליך לעדכן אותו', 'error');
		}

	}


	//Initializing colors array
	function copyColorsArray(){

		window.bidit_globals.g_colorsStock = new Array();
		arrayShuffle(window.bidit_globals.g_COLORS_FIRST);
		arrayShuffle(window.bidit_globals.g_COLORS_PERMANENT);
		window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_FIRST);
		window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_PERMANENT);
		window.bidit_globals.g_colorsStock = window.bidit_globals.g_colorsStock.concat(window.bidit_globals.g_COLORS_EXTRA);
		window.bidit_globals.g_colorsStock.reverse();
		
	}



	function checkIfSwitchNeeded(){
		if (localStorage.currSemesterStored == '1') {

			window.bidit_globals.g_viaLcalStorage = true;
			window.setTimeout(function () {
				$('#semesterB > a').click();
			}, 1);

		}

		else{
			getFacultiesAndDepartsFromAjax();
		}
	}

	/*================================================================================================
	 *                                      Miscellaneous 
	 *================================================================================================
	 */

	$('#connectTAU').click(function(){
		//window.open('http://mytau.tau.ac.il');
		window.open('https://iims.tau.ac.il/tal/Default.aspx?');
		$('#connectTAU').removeClass('btn-large');
		$('#connectTAU').addClass('btn-small');
		$('#sekerUniLogin').addClass('hide');

	});

	$('#IDNumber').keypress(function (e) {
		if (e.which == 13){
			$('#IDEnter').click();
		}
	});

	$('#IDEnter').click(function(){
		var id = $('input[id=IDNumber]').val();
		var address = 'https://iims.tau.ac.il/tal/Seker/Seker_Result.aspx?id='+id+'&src=maj&key='+  window.bidit_globals.g_currCourseProfile ;
		window.open(address);

	});

	function checkIfSignedInToUniversity(address){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/check-uni-login/",
			dataType: 'json',
			data: { },
			success: function(data){
				if(data.OK == '1'){
					window.open(address);
				}
				else{
					$('#sekerUniLogin').removeClass('hide');
				}

			}
		});//ajax closed
	}

	$('#moreOnSeker').popover({ placement: 'bottom', html:true, 
		content: 'הנתונים נגישים רק לבעלי שם משתמש וסיסמה בשרתי האוניברסיטה. כדי לצפות בנתונים עליך להיות מחובר למערכת האוניברסיטאית.<br/>בלחיצה על "התחבר" תועבר למסך ההתחברות ולאחר שתתחבר תוכל להיכנס לתוצאות הסקר ע"י הזנת מספר זהות. במידה והנך מחובר כבר דלג על שלב ההתחברות.<br/>הערה: יתכן ותאלץ לאשר חלונות קופצים.' });

	$('#myCoursesStack').on('mouseenter',function(){
		$('#clearTimeTable').css('opacity','100');
		$('#unChooseCourses').css('opacity','100');

	});

	$('#myCoursesStack').on('mouseleave',function(){
		$('#clearTimeTable').css('opacity','0.7');
		$('#unChooseCourses').css('opacity','0.7');

	});

	$('#clearTimeTableDiv').on('mouseenter',function(){
		$('#clearTimeTableDiv').tooltip('show');
		$('#clearTimeTableDiv').css('cursor','pointer');
		$('#clearTimeTable').css('cursor','pointer');

	});

	$('#clearTimeTableDiv').on('mouseleave',function(){
		$('#clearTimeTableDiv').tooltip('hide');
		$('#clearTimeTableDiv').css('cursor','default');
	});


	function getGroupNumsArr(courseInfoObj){
		var groupsNumArr = [];

		$.each(courseInfoObj.kvutzaData,function(){
			var gNum = this.gNum;
			groupsNumArr.push(gNum);
		});

		return groupsNumArr;
	}

	$('#clearTimeTableDiv').on('click',function(){
		var currSemester = window.bidit_globals.g_currSemester;
		var otherSemester = getOtherSemester(currSemester);

		while(window.bidit_globals.g_chosenCoursesArr[currSemester].length != 0){
			var cNum = (window.bidit_globals.g_chosenCoursesArr[currSemester])[0];

			//If the course is yearly, delete it from all semesters
			var cAccordIndex = findCourseIndexInAccordionsArr(currSemester, cNum);
			var courseInfoObj = window.bidit_globals.g_allSemestersAccordions[currSemester][cAccordIndex];
			var isCourseYearly = checkIfCourseIsYearly(courseInfoObj);
			var groupNums = [];
			groupNums = getGroupNumsArr(courseInfoObj);
			if(isCourseYearly){
				deleteFromDataStructAnotherSem(cNum,groupNums,otherSemester);	
			}

			removeCourseFromMain(cNum,false);

		}	

		//Init total hours
		window.bidit_globals.g_totalHoursArr[currSemester] = '0';
		window.bidit_globals.g_totalZchutHoursArr[currSemester] = 0.0;
		
		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

	});


	$('#clearTimeTableDiv').tooltip({ placement: 'top', animation: 'false', 
		title: 'רוקן את מאגר הקורסים' });

	$('#unChooseCoursesDiv').tooltip({ placement: 'top', animation: 'false', 
		title: 'נקה קורסים שנבחרו' });


	$('#unChooseCoursesDiv').on('mouseenter',function(){
		$('#unChooseCoursesDiv').tooltip('show');
		$('#unChooseCoursesDiv').css('cursor','pointer');

	});

	$('#unChooseCoursesDiv').on('mouseleave',function(){
		$('#unChooseCoursesDiv').tooltip('hide');
		$('#unChooseCoursesDiv').css('cursor','default');
	});

	$('#unChooseCoursesDiv').on('click',function(){
		InitSchedualDisplay();		
	});

	$('#yearTab > a').click(function () { return false; });

	$('#yearTab > a').empty();
	$('#yearTab > a').append('מעודכן ל'+window.bidit_globals.g_currHebrewYear);

	guidesLink

	$('#facebookLogo').on('mouseover',function(){
		$('#facebookLogo').css("cursor"," pointer");
	});


	$('#facebookLogo').click(function(){
		window.open("https://www.facebook.com/pages/Bid-it/1211188905687121?fref=ts");
	});

	$('#guidesLink').on('mouseover',function(){
		$('#guidesLink').css("cursor"," pointer");
	});


	$('#guidesLink').click(function(){
		window.open("http://new.tau.ac.il/guides1");
	});

	$('#agudaLink').on('mouseover',function(){
		$('#agudaLink').css("cursor"," pointer");
	});

	$('#agudaLink').click(function(){
		window.open("http://student.co.il/");
	});


	/*================================================================================================
	 *                                       Welcome Page
	 *================================================================================================
	 */
	function welcomeWebStorage(){

		/*1-SHOW WELCOME , 0-DONT SHOW*/

		if(typeof(Storage)!=="undefined"){
			if (localStorage.showWelcomePage){
				if (localStorage.showWelcomePage == 1) {
					document.getElementById("neverShowAgain").checked = false;
					$('#welcomeModal').modal('show');
				}
				if (localStorage.showWelcomePage == 0) {
					document.getElementById("neverShowAgain").checked = true;
				}
			}
			else {
				localStorage.showWelcomePage=1;
				welcomeWebStorage();
			}
		}

		/*browser doesnt support*/
		else
		{
			$('#neverShowAgainDiv').empty();
		}
	}


	$('#neverShowAgain').change(function() {

		if ($("#neverShowAgain").is(':checked')) {
			localStorage.showWelcomePage = 0;
			document.getElementById("neverShowAgain").checked = true;
		}
		else {
			localStorage.showWelcomePage = 1;
			document.getElementById("neverShowAgain").checked = false;
		}

	});


	$('#skipWelcome').click(function() {
		$('#welcomeModal').modal('hide');
	});





	$('#readMore').click(function() {

	});




	/*================================================================================================
	 *                                       AUTOCOMPLETE
	 *================================================================================================
	 */

	function initAutoComplete(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/get-autoComplete-courses/",
			dataType: 'json',
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (window.bidit_globals.g_currSemester+1) },

				success: function(data){

					createRelevantAutoComplete(data);
				}
		});//ajax closed
	}

	function createRelevantAutoComplete(data){
		courses = [];
		map = {};

		var courseData = data.Courses;

		$.each(courseData, function (i, course) {
			map[course.courseName] = course;
			courses.push(course.courseName);
		});

		$('#search').typeahead({
			source: function (query, process) {
				process(courses);
			}, 

			items: 10, 

			minLength: 1,

			updater: function (item) {
				if(map[item] == undefined){ /* do nothing if there's no course searched for */}
				else{
					selectedCourse = map[item].courseCode;

					$('#courseTable').empty();
					$('#chosenCourses').empty();

					var tempChosenCourseArr=[];

					if(window.bidit_globals.g_chosenCoursesArr[window.bidit_globals.g_currSemester].indexOf(selectedCourse) == -1){
						tempChosenCourseArr.push(selectedCourse);
					}




					/* Ask chosen courses info from server and present it on main screen */
					chosenCoursesAjaxRequest(tempChosenCourseArr,false);

					//Data need to be saved
					if(window.bidit_globals.g_currSemester == 0){
						localStorage.isDataSaved_A = '0';

					}
					else{
						localStorage.isDataSaved_B = '0';
					}

					/*if there are courses show the optimizer button*/
					showOrHideOptimizeButton();

					return null;

				}

			}
		});
	}


	/*================================================================================================
	 *                                       Course Catalog Screen
	 *================================================================================================
	 */

	function getFacultiesAndDepartsFromAjax(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/faculties-list/",
			dataType: 'json',
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (window.bidit_globals.g_currSemester+1) },
				success: function(data)
				{
					InitFacultiesAndDeparts(data);
				}
		});//ajax closed
	}


	/* Creating the faculties accordion, with all the departments below them */
	function InitFacultiesAndDeparts(data){
		var facultiesArr = data.faculties;
		window.bidit_globals.g_facultiesAndDeparts = data.faculties;

		// Add faculty filter accordion
		$('<div class="accordion"><div id="facultyFilter" width="100%" class="accordion-group">' +
				'<div width="100%" class="accordion-heading">' +
				'<a id="aFacultyFilter" class="accordion-toggle" data-toggle="collapse" data-parent="#filters-accordion" href="#facultiesList">' +
				'<br/>' + 
				'בחר פקולטה' + 
				'</a>' + 
				'</div>' + 
				'<div id="facultiesList" width="100%" class="accordion-body collapse in pre-scrollable" style="overflow-y:auto; max-height:150px;">' +
				'<ul id="facultiesListInner" class="accordion-inner unstyled">' +
				'</ul>' +
				'</div>' +
		'</div></div>').appendTo('#filters-accordion');


		for(var i=0; i < facultiesArr.length; i++){
			$('<li id="' + facultiesArr[i].fNum + '" class="depart-cell-hover faculty-filter-li">' + facultiesArr[i].fName +'</li>').appendTo('#facultiesListInner');	 
		}


		// Add department filter accordion
		$('<div class="accordion"><div id="departFilter" width="100%" class="accordion-group">' +
				'<div width="100%" class="accordion-heading">' +
				'<a id="aDepartFilter" class="accordion-toggle" data-toggle="collapse" data-parent="#filters-accordion" href="#departList">' +
				'<br/>' + 
				'בחר חוג' + 
				'</a>' + 
				'</div>' + 
				'<div id="departList" width="100%" class="accordion-body collapse pre-scrollable" style="overflow-y:auto; max-height:150px;">' +
				'<ul id="departListInner" class="accordion-inner unstyled">' +
				'</ul>' +
				'</div>' +
		'</div></div>').appendTo('#filters-accordion');

		$('#departFilter').hide();


		// Add day filter accordion
		$('<div class="accordion"><div id="dayFilter" width="100%" class="accordion-group">' +
				'<div width="100%" class="accordion-heading">' +
				'<a id="aDayFilter" class="accordion-toggle" data-toggle="collapse" data-parent="#filters-accordion-2" href="#dayList">' +
				'<br/>' + 
				'סנן קורסים לפי יום' + 
				'</a>' + 
				'</div>' + 
				'<div id="dayList" width="100%" class="accordion-body collapse pre-scrollable" style="overflow-y:auto; max-height:150px;">' +
				'<ul id="dayListInner" class="accordion-inner unstyled">' +
				'<li id="dayFilter0" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;כל הימים</li>'+
				'<li id="dayFilter1" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;א</li>'+
				'<li id="dayFilter2" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;ב</li>'+
				'<li id="dayFilter3" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;ג</li>'+
				'<li id="dayFilter4" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;ד</li>'+
				'<li id="dayFilter5" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;ה</li>'+
				'<li id="dayFilter6" class="depart-cell-hover day-filter-li">&nbsp;&nbsp;&nbsp;&nbsp;ו</li>'+
				'</ul>' +
				'</div>' +
		'</div></div>').appendTo('#filters-accordion-2');

		$('#dayFilter').hide();
		$('#idChosenFilters').hide();

	}

//	------------------------------------ courses filters ----------------------------------------------------

	/* Changes the filter button color when its clicked */
	function changeFilterButtonCss(prevFilterNum,newFilterNum){
		var prevFilter = '#' + prevFilterNum;
		var newFilter = '#' + newFilterNum;

		if(prevFilter != '#NOT_CHOSEN'){
			$(prevFilter).removeClass('depart-cell-highlight');
			$(prevFilter).addClass('depart-cell-hover');
			$(prevFilter).css('cursor','pointer');
		}

		$(newFilter).removeClass('depart-cell-hover');
		$(newFilter).addClass('depart-cell-highlight');
		$(newFilter).css('cursor','default');
	}


	function userChoseFaculty(chosenFacultyNum, chosenFacultyName){
		var facultiesArr = window.bidit_globals.g_facultiesAndDeparts;

		$('#departListInner').empty();
		$('#courseTable').empty();

		for(var i=0; i < facultiesArr.length; i++){
			if(chosenFacultyNum == facultiesArr[i].fNum){
				var departsArr = facultiesArr[i].fDeparts;
				for(var j=0; j < departsArr.length; j++){
					$('<li id="' + departsArr[j].dNum + '" class="depart-cell-hover depart-filter-li">' + departsArr[j].dName +'</li>').appendTo('#departListInner');
				}
			}
		}

		window.bidit_globals.g_currChosenDepart = 'NOT_CHOSEN';
		window.bidit_globals.g_currChosenDepartName = '';

		$('#idChosenFilters').show();
		$('#idChosenFiltersCrumbs').empty();
		$('#idChosenFiltersCrumbs').append('<li>' + chosenFacultyName + '<span class="divider">/<span></li>');
	}

	/* The user clicked on a faculty and chose it */
	$('#filters-accordion').delegate('.faculty-filter-li','click',function() {

		var chosenFacultyNum = $(this).attr('id');
		var chosenFacultyName = $(this).text();

		if(window.bidit_globals.g_currChosenFacultyNum != chosenFacultyNum){


			// When choosing faculty: automatically the departments filter opened, the day filter is hidden
			$('#facultiesList').collapse('hide');
			$('#departFilter').show();
			$('#departList').collapse('show');
			$('#dayFilter').hide();

			facultychoose(chosenFacultyNum, chosenFacultyName);

			saveCourseCatalogDetails();

		}



	});
	function facultychoose(chosenFacultyNum,chosenFacultyName){

		changeFilterButtonCss(window.bidit_globals.g_currChosenFacultyNum, chosenFacultyNum);

		window.bidit_globals.g_currChosenFacultyName = chosenFacultyName;
		window.bidit_globals.g_currChosenFacultyNum = chosenFacultyNum;

		userChoseFaculty(chosenFacultyNum,chosenFacultyName);
	}


	function coursesByDepartAjaxRequest(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/courses-list-by-dept/",
			dataType: 'json',
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (window.bidit_globals.g_currSemester+1),
				'dept_num': window.bidit_globals.g_currChosenDepart },
				success: function(data)
				{
					showCourseList(data.courses);
				}
		});//ajax closed
	}

	/* The user clicked on a department and chose it */
	$('#filters-accordion').delegate('.depart-filter-li','click',function() {

		if(window.bidit_globals.g_isFirstTimeOnCatalog){
			window.bidit_globals.g_isFirstTimeOnCatalog = false;
			$('#departList').collapse('hide');
		}

		var departLi = $(this);
		var clickedDepart = departLi.attr('id');
		var clickedDepartName = departLi.text();
		$('#idChosenFiltersCrumbs').empty();
		$('#idChosenFiltersCrumbs').append('<li>' + window.bidit_globals.g_currChosenFacultyName + '<span class="divider">/<span></li>');
		$('#idChosenFiltersCrumbs').append('<li>' + clickedDepartName + '<span class="divider">/<span></li>');
		// If the user chose a different department and not the current one
		if(window.bidit_globals.g_currChosenDepart != clickedDepart){
			departmentchoose(departLi,clickedDepart,clickedDepartName);
			saveCourseCatalogDetails();

		}

	});

	/* The user clicked on a day filter and chose it */
	$('#filters-accordion-2').delegate('.day-filter-li','click',function() {

		var strChosenDay = $(this).attr('id').substr(9);
		var strChosenDayName = $(this).text();
		var chosenDayNum = parseInt(strChosenDay);

		// If the user chose a different day and not the current one
		if(window.bidit_globals.g_currChosenDayNum != strChosenDay){
			changeFilterButtonCss('dayFilter' + window.bidit_globals.g_currChosenDayNum, 'dayFilter' + strChosenDay);

			window.bidit_globals.g_currChosenDayNum = strChosenDay;
		}


		//Updating crumbs
		$('#idChosenFiltersCrumbs').empty();
		$('#idChosenFiltersCrumbs').append('<li>' + window.bidit_globals.g_currChosenFacultyName + '<span class="divider">/<span></li>');
		$('#idChosenFiltersCrumbs').append('<li>' + window.bidit_globals.g_currChosenDepartName + '<span class="divider">/<span></li>');

		if(chosenDayNum == 0){
			coursesByDepartAjaxRequest();
			return;
		}
		else{
			$('#idChosenFiltersCrumbs').append('<li>יום' + ' ' + $.trim(strChosenDayName) + '<span class="divider">/<span></li>');
		}

		//Request for all the courses of the current department and in the chosen day
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/courses-list-by-dept-and-day/",
			dataType: 'json',
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (window.bidit_globals.g_currSemester+1),
				'dept_num': window.bidit_globals.g_currChosenDepart,
				'day_str': chosenDayNum },
				success: function(data)
				{
					showCourseList(data.courses);
				}
		});//ajax closed
		saveCourseCatalogDetails();

		return;
	});

	function departmentchoose(departLi,clickedDepart,clickedDepartName){


		$('#dayFilter0').addClass('depart-cell-highlight');
		if(window.bidit_globals.g_currChosenDayNum != 0){
			$('#dayFilter' + window.bidit_globals.g_currChosenDayNum).removeClass('depart-cell-highlight');
			$('#dayFilter' + window.bidit_globals.g_currChosenDayNum).addClass('depart-cell-hover');
			window.bidit_globals.g_currChosenDayNum = 0;
		}

		$('#dayFilter').show();

		changeFilterButtonCss(window.bidit_globals.g_currChosenDepart, clickedDepart);

		window.bidit_globals.g_currChosenDepartName = clickedDepartName;
		window.bidit_globals.g_currChosenDepart = clickedDepart;

		coursesByDepartAjaxRequest();


	}

//	------------------------------------end of courses filters ----------------------------------------------------


	//the user clicked on choose courses
	$('#chooseCoursesDiv').click(function(){
		var tempCatalogData = null;
		if(window.bidit_globals.g_currSemester==0){
			tempCatalogData=localStorage.getItem('catalog_modal_details_semestera');

		}
		else{
			tempCatalogData=localStorage.getItem('catalog_modal_details_semesterb');

		}
		if(tempCatalogData==null){
			$('#idChosenFiltersCrumbs').empty();
			$('#chosenCourses').empty();
		}
		else{
			if(tempCatalogData != '-100'){
				tempCatalogData =JSON.parse(tempCatalogData);
				$('#departFilter').show();
				$('#chosenCourses').empty();
				$('#idChosenFiltersCrumbs').empty();
				$('#idChosenFiltersCrumbs').append('<li>' + window.bidit_globals.g_currChosenFacultyName + '<span class="divider">/<span></li>');

				window.bidit_globals.g_newChosenCoursesArr=tempCatalogData['ccoursenums'];

				facultychoose(tempCatalogData['cfacultynum'],tempCatalogData['cfacultyname']);

				var departnum= tempCatalogData['cdepartnum'];
				var departname = '';
				var tempdepartLi = null;
				if(departnum != 'NOT_CHOSEN'){
					departname = tempCatalogData['cdepartname'];
					tempdepartLi = $('#'+departnum);

					departmentchoose(tempdepartLi,departnum,departname);
					tempdepartLi.removeClass('depart-cell-hover')
					tempdepartLi.addClass('depart-cell-highlight');
					tempCourseArray=window.bidit_globals.g_newChosenCoursesArr;
					tempCourseArrayNames=tempCatalogData['ccoursenames'];

					for(var i=0;i<tempCourseArray.length;i++){
						var courseNum=tempCourseArray[i][0];
						var courseName=tempCourseArray[i][1];

						$('<div class="row-fluid cl-' + courseNum +'"id="cc'+courseNum +'" data-cNum='+courseNum+'><div class="span1"><a id="courseRemoveButton"><i  class="course-action-hover icon-remove icon-large"  ></i></a></div><div class="span1"><a id="chosencourseinfoBtn"  href="#courseProfileModal" data-dismiss="modal"><i id="chosencourseinfo" class="course-action-hover icon-info-sign"  ></i></a></div><div class= "span10">' + courseName + '</div></div>').appendTo('.chosenCourses');
					}

					$('#idChosenFiltersCrumbs').append('<li>' + window.bidit_globals.g_currChosenDepartName + '<span class="divider">/<span></li>');
				}

			}

		}

	});

	/* Shows the courses of the chosen department - in the middle part of the window */
	function showCourseList(coursesArr){
		var currSemester = window.bidit_globals.g_currSemester;
		// Delete the previous courses list
		$('#courseTable').empty();

		if(coursesArr.length == 0){
			$('#courseTable').append('<div style="text-align:center; font-weight:bold;">' + '- לא קיימים קורסים עבור הסינון הנוכחי -' + '</div>');
		}

		$.each(coursesArr,function(){

			var courseCellClass ="depart-cell-highlight";
			if ( getIndexForNewChosenCoursesArr(this.cNum)==-1){
				courseCellClass = "depart-cell-hover";
			}

			// Adding the courses names and an info button to the courses list on screen
			if (window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(this.cNum)!=-1){
				courseCellClass = "course-cell-disabled";
			}
			
			$('#courseTable').append('<div class="row-fluid '+ courseCellClass +'" id="lc' + this.cNum + '" data-cNum="'+this.cNum+'"data-cName="'+this.cName+' " data-facultyNum="' + window.bidit_globals.g_currChosenFacultyNum  + '">' +
					'<div id="info" class="span2 clInfo"  style="margin-top:7px;"><a id="infoBtn" class="btn btn-mini btn-primary" href="#courseProfileModal" data-dismiss="modal" style="font-size:small; font-family:Monospace;"><strong>i</strong></a></div>' +
					'<div id="course" class="span10"   style="margin-top:2px; margin-bottom:2px; direction:rtl;">' + this.cName + '</div>' +
			'</div>');


			if (window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(this.cNum)!=-1){
				$("this").unbind('mouseenter mouseleave');
			}
		});
	}

	/* The user clicked X on a course from the chosen courses tab*/
	$('#chosenCourses').delegate('#courseRemoveButton', 'mouseenter', function() {


		$(this).addClass('icon-white');
	});
	
	$('#chosenCourses').delegate('#courseRemoveButton', 'mouseleave', function() {


		$(this).removeClass('icon-white');
	});

	$('#chosenCourses').delegate('#courseRemoveButton', 'click', function() {
		var currSemester = window.bidit_globals.g_currSemester;

		var courseNum =$(this).closest('div.row-fluid').attr('data-cNum');
		var courseName =$(this).closest('div.row-fluid').attr('data-cName');

		$(this).closest('div.row-fluid').remove();

		$('#lc'+courseNum).removeClass('depart-cell-highlight');
		$('#lc'+courseNum).removeClass('course-cell-disabled');
		$('#lc'+courseNum).addClass('depart-cell-hover');
		var tempTupple = [courseNum,courseName]
		window.bidit_globals.g_newChosenCoursesArr.splice( getIndexForNewChosenCoursesArr(courseNum),1);
		
		saveCourseCatalogDetails();
	});	 

	/* The user clicked on a course and chose it or made it unchosen */
	$('#courseTable').delegate('#course', 'click', function() {

		var isDisabled=$(this).closest('div.row-fluid').hasClass('course-cell-disabled');
		if (isDisabled==false){

			var currSemester = window.bidit_globals.g_currSemester;
			var courseNum = $(this).closest('div.row-fluid').attr("data-cNum");
			var courseName = $(this).text();
			
			//checks if the course already exist... if not will return -1
			var index_In_g_chosenCoursesArr =window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(courseNum);
			var index_In_g_newChosenCoursesArr =getIndexForNewChosenCoursesArr(courseNum);
			// Gets course' element current class
			var isHover = $(this).closest('div.row-fluid').hasClass("depart-cell-hover");
			if(isHover == true){
				// Updates current class of course' cell: chosen or nor chosen
				$(this).closest('div.row-fluid').removeClass('depart-cell-hover');
				$(this).closest('div.row-fluid').addClass('depart-cell-highlight');
				$(this).closest('div.row-fluid').addClass('highlightedCourses');

				//Adds the chosen course to the chosen courses list (on screen and global array)
				if (index_In_g_newChosenCoursesArr == -1 ){
					//$('<div " class="chosenCourse cl-' + courseNum +'" id="'+courseNum +'"><i id="courseRemoveButton" class=" icon-remove icon-large"  ></i>' + courseName + '</div>').appendTo('.chosenCourses');
					// $('<tr class="cl-' + courseNum +'"id="cc'+courseNum +'" data-cNum='+courseNum+'><td>' + courseName + '</td><td><i id="chosencourseinfo" class="course-action-hover icon-info-sign"  ></i></td><td><i id="courseRemoveButton" class="close icon-remove icon-large"  ></i></td></tr>').appendTo('.chosenCourses');
					$('<div class="row-fluid cl-' + courseNum +'" id="cc'+courseNum +'" data-cNum="'+courseNum+'" data-cName="'+courseName+'"><div class="span1"><a id="courseRemoveButton"><i class="course-action-hover icon-remove icon-large"></i></a></div><div class="span1"><a id="chosencourseinfoBtn"  href="#courseProfileModal" data-dismiss="modal" data-toggle="modal"><i id="chosencourseinfo" class="course-action-hover icon-info-sign"></i></a></div><div class="span10">' + courseName + '</div></div>').appendTo('.chosenCourses');
					//guy end
					var tempTupple = [courseNum,courseName];
					window.bidit_globals.g_newChosenCoursesArr.push(tempTupple);
				}
			}
			else{
				// Updates current class of course' cell: chosen or nor chosen
				$(this).closest('div.row-fluid').removeClass('depart-cell-highlight');
				$(this).closest('div.row-fluid').addClass('depart-cell-hover');


				// Removes the chosen course from the chosen courses list (and global array)
				$('.cl-' + courseNum).remove();
				window.bidit_globals.g_newChosenCoursesArr.splice(getIndexForNewChosenCoursesArr(courseNum),1);
			}
		}
		
		saveCourseCatalogDetails();
	});

	/* The user touched an info button with the mouse */
	$('#courseTable').delegate('#infoBtn', 'mouseenter', function() {
	
		onClickInfoBtn(this);

	});

	$('#chosenCourses').delegate('#chosencourseinfoBtn', 'mouseenter', function() {
		$(this).addClass('icon-white');
		onClickInfoBtn(this);

	});
	
	$('#chosenCourses').delegate('#chosencourseinfoBtn','mouseleave',function(){
		$(this).removeClass('icon-white');
	});

	function onClickInfoBtn(btn){
		window.bidit_globals.g_currCourseProfile = $(btn).closest('div.row-fluid').attr("data-cNum");
		window.bidit_globals.g_currChosenInfoBtnDepart = window.bidit_globals.g_currCourseProfile.substring(0,4);
		window.bidit_globals.g_isProfileOpenedFromMain = false;
		courseProfileInit();
		$(btn).unbind('click');
		$(btn).on('click', function(){

			$('#tab3x').empty();
			abortAllSyllabusRequests();
			syllabusRequestAjax = $.ajax({
				type: "GET",
				url: "/ajax/get-syllabus/",
				dataType: 'json', 
				data: { 'university': window.bidit_globals.g_currUniversity,
					'semester': (window.bidit_globals.g_currSemester+1),
					'course_num': window.bidit_globals.g_currCourseProfile },
					success: function(data)
					{
						syllabusRequestAjax = null;
						showCourseSyllabus(data);
					}
			});//ajax closed

			$.when(getCurrentCourseFromAjax()).done(function(a1, textStatus, jqXHR){
				unAssignCourseProfileData();
				checkIfCanAssignProfileData(a1);
				
				//open course profile
				$('#courseProfileModal').modal('show');
			});
		});

	}	


	$('#addCourses').click(function(){
		//Need to save data

		if(window.bidit_globals.g_currSemester == 0){
			localStorage.isDataSaved_A = '0';
		}
		else{
			localStorage.isDataSaved_B = '0';
		}

		window.bidit_globals.g_toSaveSelection = true;

		$('#chosenCourses').empty();
		$('.highlightedCourses').addClass('course-cell-disabled');
		$('.highlightedCourses').removeClass('depart-cell-highlight');
		$('.highlightedCourses').removeClass('highlightedCourses');
		
		var tempCourseArrForAjax =  getCourseNumbersFromNewChosecourses();

		if(tempCourseArrForAjax.length > 0){
			chosenCoursesAjaxRequest(tempCourseArrForAjax,false);

			/*if there are courses show the optimizer button*/
			showOrHideOptimizeButton();
		}

		window.bidit_globals.g_newChosenCoursesArr = new Array();

		saveCourseCatalogDetails();




	});

	function getOtherSemester(intSemesterNum){
		if(intSemesterNum == 1){
			return 0;
		}
		else{
			return 1;
		}
	}

	function checkIfCourseIsYearly(courseObj){
		if (courseObj.isYearly == true || courseObj.isYearly == undefined){
			return true;
		}
		else{
			return false;
		}
	}

	/* Gets the information for chosen courses, to be displayed on the main screen */
	function chosenCoursesAjaxRequest(coursesList,isScheduleLoaded){
		openBlockUI();
		var counter = 0;
		var currSemester = window.bidit_globals.g_currSemester;
		var otherSemester = getOtherSemester(currSemester);
		var yearlyCoursesNums = [];

		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/chosen-courses-info/",
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (currSemester+1),
				'courses_list': coursesList},
				traditional: true,
				dataType: 'json',
				success: function(data)
				{

					$.each(data.coursesInfo,function(){
						if (checkIfInAccordion(this, currSemester) == false){
							window.bidit_globals.g_allSemestersAccordions[currSemester].push(this);
							counter++;

							var isCourseYearly = checkIfCourseIsYearly(this);
							var cNum = this.cNum;
							if(isCourseYearly){
								yearlyCoursesNums.push(cNum);
							}
						}
					});

					//Presents the chosen courses in the accordion on main screen
					addCoursesToMain(counter,currSemester);

					if(isScheduleLoaded == false){
						addYearlyCoursesToOtherSemester(otherSemester, yearlyCoursesNums);	
					}

					coursesList=[];

				},

				complete: function () {
					closeBlockUI();
				}
		});//ajax closed
	}


	function addYearlyCoursesToOtherSemester(currSemester, yearlyCoursesNumsArr){
		var counter = 0;

		var requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/chosen-courses-info/",
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (currSemester+1),
				'courses_list': yearlyCoursesNumsArr},
				traditional: true,
				dataType: 'json',
				success: function(data)
				{

					$.each(data.coursesInfo,function(){
						if (checkIfInAccordion(this, currSemester) == false){
							window.bidit_globals.g_allSemestersAccordions[currSemester].push(this);
							counter++;
						}
					});

					//Presents the chosen courses in the accordion on main screen
					addCoursesToMain(counter,currSemester);
				}
		});
	}

	$('#chooseFaculties').click(function(){
		$('#dropdownDeparts').css('position', 'absolute');
	});


	$('#courseCatalogExit1').click(function(){
		window.bidit_globals.g_toSaveSelection = false;
		$('#courseCatalogModal').modal('hide');
	});

	$('#courseCatalogExit2').click(function(){
		window.bidit_globals.g_toSaveSelection = false;
		$('#chosenCourses').empty();
		window.bidit_globals.g_newChosenCoursesArr=[];
		saveCourseCatalogDetails();
	});

	/* The scrolling of the course catalog modal */ 
	$('#courseCatalogModal').css('max-height', '90%');


	function checkIfInAccordion(course, semesterNum){

		for (var i=0 ; i<window.bidit_globals.g_allSemestersAccordions[semesterNum].length ; i++){
			if (window.bidit_globals.g_allSemestersAccordions[semesterNum][i].cNum == course.cNum) return true;
		}

		return false;

	}



	/*================================================================================================
	 *                                       Course Profile Screen
	 *================================================================================================
	 */

	function courseProfileInit(){
		if(!window.bidit_globals.g_isProfileOpenedFromMain){
			$('#closeBackToCatalog').show();
			$('#closeBackToMain').hide();
			$('#backToCatalog').show();
			$('#backToMain').hide();
		}
		else{
			$('#closeBackToCatalog').hide();
			$('#closeBackToMain').show();
			$('#backToMain').show();
			$('#backToCatalog').hide();
		}


		$('#courseProfileTabs li').each(function(){
			$(this).removeClass('active'); 
		});
		$('#coursProfileTabsContent div').each(function(){
			$(this).removeClass('active'); 
		});

		$('#courseProfileTabs a:first').tab('show');
		$('#coursProfileTabsContent div:first').tab('show');


	}

	function abortAllSyllabusRequests(){
		if(syllabusRequestAjax != null){
			syllabusRequestAjax.abort();	
		}

	}

	function showCourseSyllabus(obj){
		$('#tab3x').empty();
		$.each(obj.syllabus,function(){
			$('#tab3x').append('<p style="direction: rtl !important;">'+this.syl+'</p>');
		});
	}


	function getCurrentCourseFromAjax(){
		abortAllRequests();
		$.ajaxSetup({
			responseFields: {
				"json": "responseJSON"
			}
		});
		/*for not duplicates information about course in profile*/
		abortAllRequests();
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/course-profile-info/",
			dataType: 'json', 
			data: { 'university': window.bidit_globals.g_currUniversity,
				'semester': (window.bidit_globals.g_currSemester+1),
				'department': window.bidit_globals.g_currChosenInfoBtnDepart,
				'course_num': window.bidit_globals.g_currCourseProfile }

		});//ajax closed
		return requestAjax;
	}

	function checkIfCanAssignProfileData(data){
		if (window.bidit_globals.g_currCourseUploaded==false){
			$.each(data.courseInfo,function(){

				window.bidit_globals.g_currCourseProfile = this.cNum;
				assignCourseProfileData(this);
				getTableData2(this);
				getChartData(this);
				window.bidit_globals.g_currCourseUploaded = true;

				//will make table_div hidden when bid statistics open
				$('#table_div').show();
				$('#chart_div').hide();

				$('#helpGrafText').hide();
				$('#tavlaStyleBtn').show();
				$('#grafStyleBtn').hide();

			});
		}
	}
	function assignCourseProfileData(course){
		$('#courseNameId').text(checkIfDef(course.cName));
		$('#amountHours').text(checkIfDef(course.hoursNum));
		$('#amountPoints').text(analyzeZchut(checkIfDef(course.zchutHours)));
		$('#ProfileModalLabel').text(function(){
			return checkIfDef(course.cName)+ ' (' + checkIfDef(course.cNum) + ')'; 
		});
		$('#ProfileModalLabelSmall').empty();
		$('#ProfileModalLabelSmall').append(function(){
			var semesterString;
			var yearString;
			var facultyString;
			var departmentString;
			var retString;

			retString = "";

			if (checkIfDef(parseNumToSemester(checkIfDef(course.semester)))){
				if (course.isYearly == false) {
					retString += 'סמסטר '+checkIfDef(parseNumToSemester(checkIfDef(course.semester))) + "'";
				}
				if (course.isYearly == true) {
					retString += '<span style="color: blue;">קורס שנתי</span>';
				}
				if (course.isYearly == undefined) {
					retString += '<span style="color: blue;">קורס שנתי</span>';
				}
			}

			if (checkIfDef(course.cYear)!=''){
				retString += ', ' + checkIfDef(course.cYear);
			} 

			if (checkIfDef(course.depart)!=''){
				retString += ', ' + checkIfDef(course.depart) ;
			}

			if (checkIfDef(course.faculty)!=''){
				retString += ', ' + checkIfDef(course.faculty) ;
			}


			return retString;
		});


		$('#marzimTeble').append(function() {
			var retString = "";
			var havurut = new Array();
			var counter=1;
			var kindBreak = true;
			var currNum = "";

			/*loop to count number of havurut*/

			for (var i=0 ; i< course.kvutzaData.length ; i++){

				if (!havurut.contains(course.kvutzaData[i].havura)){
					havurut.push(course.kvutzaData[i].havura);
				}
			}

			/*setting table headings*/

			if (havurut.length>0){
				retString += ' <thead><tr class="info" align="center">'+
				'<th><strong>סוג</strong></th>'+
				'<th><strong>מספר</strong></th>'+
				'<th><strong></strong></th>'+
				'<th><strong>מרצה</strong></th>'+
				'<th><strong>יום</strong></th>'+
				'<th><strong>שעה</strong></th>'+
				'<th><strong>מיקום</strong></th>'+
				'<th><strong>מתכונת</strong></th>'+
				'</tr> </thead><tbody>';
			}

			else {
			}


			/*loop over havurut*/	
			havurut.forEach(function(entry){
				kindBreak = true;

				/*in case tjere is more than one HAVURA*/
				if (havurut.length>1) {
					retString += "<tr class='warning profileTableHead'><td colspan='8'><strong>אפשרות "+ counter++ +"</strong></td></tr>";				
				}

				for (var i=0 ; i< course.kvutzaData.length ; i++){

					if (course.kvutzaData[i].havura==entry) {

						/*in case there is no data in days, so print one row with ofenHoraa, gNum and matconet*/
						if (course.kvutzaData[i].days.length == 0){
							retString += '<tr>' +
							'<td>' + checkIfDef(course.kvutzaData[i].ofenHoraa) +'</td>' +
							'<td>' + checkIfDef(course.kvutzaData[i].gNum) + '</td>'+
							'<td>' + "" + '</td>'+
							'<td>' + "---" + '</td>'+
							'<td>' + "---" + '</td>'+
							'<td>' + "---" + '</td>'+ 
							'<td>' + "---" + '</td>'+
							'<td>' + checkIfDef(course.kvutzaData[i].matconet) + '</td>'+
							'</tr>';

						}

						for(var j=0 ; j< course.kvutzaData[i].days.length ; j++){

							/*case of same group*/
							if (course.kvutzaData[i].gNum==currNum) {
								retString += '<tr>' +
								'<td>' + '"' +'</td>'+
								'<td>' + '"' +'</td>'+
								'<td>' + '' +'</td>'+
								'<td>' + '"' + '</td>'+
								'<td>' + checkIfDef(course.kvutzaData[i].days[j])+'</td>'+
								'<td>' +
								formatBeginEndHours(
										formatHour(checkIfDef(course.kvutzaData[i].
												beginHours[j])),
												formatHour(checkIfDef(course.kvutzaData[i].
														endHours[j]))
								)			 
								+'</td>'+ 
								'<td>' + checkIfDef(course.kvutzaData[i].place[j]) +'</td>'+
								'<td>' + checkIfDef(course.kvutzaData[i].matconet) +'</td>'+
								'</tr>';

								if (i < course.kvutzaData.length-1){
									if (course.kvutzaData[i].gNum != course.kvutzaData[i+1].gNum){
										retString += "</tbody><tbody>";	
									}
								}
							}
							/*case of new group*/
							else {	

								currNum = course.kvutzaData[i].gNum;			
								retString += '<tbody><tr>' +
								'<td>' + checkIfDef(course.kvutzaData[i].ofenHoraa) +'</td>'+
								'<td>' + checkIfDef(course.kvutzaData[i].gNum) +'</td>'+
								'<td > ' + checkExcellency(course.kvutzaData[i].lecturer[j] , course.kvutzaData[i].excellence[j]) + '</td>'+
								'<td>' + checkIfDef(course.kvutzaData[i].days[j])+'</td>'+
								'<td>' +
								formatBeginEndHours(
										formatHour(checkIfDef(course.kvutzaData[i].
												beginHours[j])),
												formatHour(checkIfDef(course.kvutzaData[i].
														endHours[j]))
								)	 
								+'<td>' + checkIfDef(course.kvutzaData[i].place[j]) +'</td>'+
								'<td>' + checkIfDef(course.kvutzaData[i].matconet) +'</td>'+
								'</tr>';

								if (i < course.kvutzaData.length-1){
									if (course.kvutzaData[i].gNum == course.kvutzaData[i+1].gNum){
										retString += "</tbody><tbody>";	
									}
								}
							}

						}
					}
				}

			});


			if (retString != "") retString+="</tbody>";
			return retString;

		});



		$('#mivhanimTable').append(function() {
			var retString = "";
			var matalotKinds = new Array();

			for (var i=0 ; i< course.kvutzaData[0].moedType.length ; i++){
				if (!matalotKinds.contains(course.kvutzaData[0].moedType[i])){
					matalotKinds.push(course.kvutzaData[0].moedType[i]);
				}

			}


			if (matalotKinds.length != 0) {

				$('#matalotHeading').append('<strong>מטלות סיום</strong>');

				retString += ' <thead><tr class="info" align="center">'+
				'<th><strong>מועד</strong></th><th><strong>תאריך</strong></th><th><strong>יום</strong></th>'+
				'<th><strong>שעת התחלה</strong></th><th><strong>שעת סיום</strong></th></tr></thead><tbody>';    
			}

			matalotKinds.forEach(function(entry) {
				retString += "<tr class='warning profileTableHead'><td colspan='5'><strong>"+entry+
				"</strong></td></tr><tbody>";

				for (var i=0 ; i< course.kvutzaData[0].moedType.length ; i++){
					if (course.kvutzaData[0].moedType[i] == entry){

						dateFormat: 'dd-mm-yy';


					var printedDate;
					if (course.kvutzaData[0].dates[i] == "------" || course.kvutzaData[0].dates[i] == "---"){
						printedDate = "---";
					}
					else {
						var examDate = new Date(dateToString(course.kvutzaData[0].dates[i]));   
						printedDate = numToDay(checkIfDef(examDate.getDay()));
					}



					retString += '<tr>' +
					'<td>' + checkIfDef(course.kvutzaData[0].moed[i]) +'</td>'+
					'<td>' + delimDate(checkIfDef(course.kvutzaData[0].dates[i]))+ '</td>'+
					'<td>' + printedDate +
					'<td>' + checkIfDef(course.kvutzaData[0].startMoedHours[i])+  '</td>'+
					'<td>' + checkIfDef(course.kvutzaData[0].endMoedHours[i])+  '</td>'+
					'</tr>' ;
					}

				}
				retString += "</tdoby>";



			});

			return retString;

		});




		$('#courseLang').append(function() {
			return analyzeLang(checkIfDef(course.language));

		});


		$('#courseVideoBoolean').append(function() {

			if (course.video==true) return '<i class="icon-ok"></i>';
			if (course.video==false) return '<i class="icon-remove"></i>';

		});

		$('#courseFinalAssignment').append(function() {
			return checkIfDef(course.matalot);

		});

	}

	function checkExcellency(lec,exc){
		if (lec == '---') '</td><td>'+lec;
		var inputExcelKinds = [];
		var excTwoKinds = {"rec":[] , "best":[]};
		if (exc != '') inputExcelKinds = exc.split('~');


		for (var i=0 ; i<inputExcelKinds.length ; i++){
			if (inputExcelKinds[i].substring(0,3) == 'rec'){
				excTwoKinds["rec"][excTwoKinds["rec"].length] = 
					inputExcelKinds[i].substring(3,7);
				continue;
			}
			if (inputExcelKinds[i].substring(0,4) == 'best'){
				excTwoKinds["best"][excTwoKinds["best"].length] = 
					inputExcelKinds[i].substring(4,8);
				continue;
			}
		}


		if (excTwoKinds["rec"].length > 0) {
			return '<img src="assets/img/Medal-Gold-icon.png"  title="'+printExcellency(excTwoKinds)+'"  valign="center" width="23" height="28" />'+
			'</td><td>'+lec;
		}

		if (excTwoKinds["best"].length > 0) {
			return '<img src="assets/img/Medal-Silver-icon.png" title="'+printExcellency(excTwoKinds)+'"  valign="center" width="23" height="28" />'+
			'</td><td>'+lec;
		}

		return '</td><td>'+lec;


	}
	function printExcellency(excTwoKinds){
		var retString = '';
		if (excTwoKinds["rec"].length > 0){
			retString += 'מצטיין רקטור בשנים: ';
			for (var x=0 ; x<excTwoKinds["rec"].length ; x++){
				if (x<excTwoKinds["rec"].length-1){
					retString += excTwoKinds["rec"][x]+', ';
				}
				else {
					retString += excTwoKinds["rec"][x];
				}
			}
		}

		if (excTwoKinds["best"].length > 0){
			if (retString != '') retString += '\n';

			retString += 'אחד מ-100 מרצים מצטיינים בשנים: ';

			for (var x=0 ; x<excTwoKinds["best"].length ; x++){
				if (x<excTwoKinds["best"].length-1){
					retString += excTwoKinds["best"][x]+', ';
				}
				else {
					retString += excTwoKinds["best"][x];
				}
			}

		}
		return retString;

	}



	function parseNumToSemester(num){

		switch (num){
		case '1':    return 'א';
		break;
		case '2':    return 'ב';
		break;
		case '3':    return 'קיץ';
		break;
		case '0':    return 'שנתי';
		break;
		}

		return num;

	}

	function parseNumSymToHebSemester(num){

		switch (num){
		case 0:    return 'א';
		break;
		case 1:    return 'ב';
		break;
		}

		return num;

	}

	function formatHour(hour){
		return hour;
	}

	function formatBeginEndHours(begin,end){

		if (begin != '---' && end != '---') return (begin+'-'+end);
		if (begin != '---' && end == '---') return begin;

		return '---';

	}

	function analyzeZchut(num){
		if (num == '0' || num <= 0) return '---';
		else return num;

	}

	function analyzeLang(lang){

		return lang;
	}

	function checkIfDef(par){
		if (par==undefined) return '---';
		if (isOnlyWhiteSpace(par)) {
			return '---';
		}
		return par;

	}

	function isOnlyWhiteSpace(word){
		var counter = 0;
		for (var i=0 ; i<word.length ; i++){
			if (word[i] == ' ') counter++;	
		}
		if (counter == word.length) return true;
		return false;
	}

	function dateToString(ds){
		if (ds.length==10){ //in case of date in format dd?mm?yyyy
			var d = ds.substring(0, 2);
			var m = ds.substring(3, 5);
			var y = ds.substring(6, 10);
		}
		else {//in case of date in format dd?mm?yy
			var d = ds.substring(0, 2);
			var m = ds.substring(3, 5);
			var y = "20" + ds.substring(6, 8);
		}
		return [y,m,d];
	}

	function delimDate(d){
		var retString = "";

		if (d.length==3) return "---";
		else{
			var day = d.substring(0, 2);
			var month = d.substring(3, 5);
			var year = d.substring(8, 10);

			if (day[0] == "0") day=day.substring(1,2);
			if (month[0] == "0") month=month.substring(1,2);

			retString = day+'/'+month+'/'+year;
		}
		return retString;

	}

	function numToDay(num){

		switch (num){
		case 0:    return 'א';
		break;
		case 1:    return 'ב';
		break;
		case 2:    return 'ג';
		break;
		case 3:    return 'ד';
		break;		
		case 4:    return 'ה';
		break;
		case 5:    return 'ו';
		break;
		case 6:    return 'ש';
		break;

		default:
			return '';
		}

	}



	function unAssignCourseProfileData(){
		$("#ProfileModalLabel").text(function(){
			return '';
		});

		$('#ProfileModalLabelSmall').text(function(){
			return '';
		});

		$("#marzimTeble").text(function(){
			return '';
		});
		$("#metargelimTable").text(function(){
			return '';
		});
		$('#matalotHeading').text(function(){
			return '';
		});
		$("#mivhanimTable").text(function(){
			return '';
		});
		$("#courseLang").text(function(){
			return '';
		});

		$("#courseVideoBoolean").text(function(){
			return '';
		});

		$("#courseFinalAssignment").text(function(){
			return '';
		});

		$("#amountHours").text(function(){
			return '';
		});

		$("#amountPoints").text(function(){
			return '';
		});

		window.bidit_globals.g_currCourseUploaded=false;

		$('#moreOnSeker').popover('hide');

	}

	Array.prototype.contains = function(obj) {
		var i = this.length;
		while (i--) {
			if (this[i] == obj) {
				return true;
			}
		}
		return false;
	}


	function openFirstStats(){
		var firstOpened = false;
		var tmp;
		$.each($("#table_table .accordion-body"),function(){
			if (firstOpened == false){
				tmp = $(this).attr('id');
				tmp = tmp.replace("data", "parent");
				$('#'+tmp).click();
				firstOpened = true;
			}
		});
	}

	$('#statsTab').click(function(){
		var toOpen = true;

		$.each($("#table_table .accordion-toggle"),function(){

			if ($(this).hasClass('collapsed')) {
				toOpen = false;
			}

		});

		if (toOpen == true){
			window.setTimeout(function () {
				openFirstStats();
			}, 150);

		}

	});


	$('#grafStyleBtn').click(function(){
		$('#table_div').show();
		$('#chart_div').hide();

		$('#tavlaStyleBtn').show();
		$('#grafStyleBtn').hide();
		$('#helpGrafText').hide();
	});

	$('#tavlaStyleBtn').click(function(){
		$('#table_div').hide();
		$('#chart_div').show();

		$('#tavlaStyleBtn').hide();
		$('#grafStyleBtn').show();
		$('#helpGrafText').show();
	});


	/*================================================================================================
	 *                                       Optimize Screen
	 *================================================================================================
	 */

	function parseNumToCourse(courseNum){
		var currSemester = window.bidit_globals.g_currSemester;
		return (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cName;
	}



	$("#optimizeModal").on('shown', function (){
		var currSemester = window.bidit_globals.g_currSemester;

		$('#mustHaveTable').text('');

		$('#mustHaveTable').append(function() {

			var retString = "";
			if (window.bidit_globals.g_chosenCoursesArr[currSemester].length==0){
				return '<tr><td>'+
				'-לא נבחרו קורסים-'
				+ '</td>'
				+ '</tr>';
			}

			for (var i=0 ; i< window.bidit_globals.g_chosenCoursesArr[currSemester].length ; i++){

				retString += '<tr class="must-have-course-cell-hover" id="' + 
				window.bidit_globals.g_chosenCoursesArr[currSemester][i] + '">'+
				'<td id="course">'+
				parseNumToCourse(window.bidit_globals.g_chosenCoursesArr[currSemester][i])
				+ '</td>'
				+ '</tr>'

			}
			return retString;
		});

		resetOptimizeDateToCurrSemester(currSemester);

	});





	$("#optimizeModal").on('hidden', function (){
		/* DO NOT DELETE!!*/
		//for debuging: see whats settings the user marked

		/*


		var tmpDebugString ="";
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester].mustHaveCourses.forEach(function(entry){
			tmpDebugString+="course: "+entry;

		});


		 */


	});


	$('#neverShowAgainOptimizeAlert').change(function() {

		if ($("#neverShowAgainOptimizeAlert").is(':checked')) {
			localStorage.showOptimizerAlert = 0;
		}
		else {
			localStorage.showOptimizerAlert = 1;
		}

	});

	/*Stop just one dropdown toggle from closing on click*/
	$('#optimizeModalFooter').delegate('#buildSystem','click',function(){

		if(typeof(Storage)!=="undefined"){

			// show alert
			if (localStorage.showOptimizerAlert != 0){
				var message1 = 'פעולה זו תבנה מערכת חדשה ותמחק את הנוכחית,';
				var message2 = 'האם ברצונך להמשיך?';
				var header1 = 'בניית מערכת אוטומטית';
				$('#alertModal').attr('name','OPTIMIZE');
				$('#alertContent').text(message1) ;
				$('#noAlert').hide();
				$('#yesAlert').hide();
				$('#cancelAlert').show();
				$('#approveAlert').show();
				$('#alertContent').text(message1);
				$('#alertQuestion').text(message2);
				$('#alertHeader').text(header1);
				$('#alertModal').modal('show');
			}

			// dont show alert, start optimizer 
			else{
				$('#optimizeModal').modal('hide');
				operateOptimizer();
			}
		}
		else{
			$('neverShowAgainQuestAlertDiv').empty();
		}
	});

	/*on click call the buildSystem button with the curren setting which are default at the page loads and changed after user change settings*/
	$('#buildForMe').click(function(){
		$('#buildSystem').click();
	});


	// Start optimizer operation
	function operateOptimizer(){
		//Data need to be saved
		if(window.bidit_globals.g_currSemester == 0){
			localStorage.isDataSaved_A = '0';

		}
		else{
			localStorage.isDataSaved_B = '0';
		}

		getOptimizerSettingsFromForm();
		$.when(getOptimizedDataFromOptimizer()).done(function(a2, textStatus, jqXHR){
			var data = a2;
			updateSchedualWithOptimizedData(data);
			/*clear and foucs on course search*/
			clearAndFocusCourseSearch();

		});
	}

	function getOptimizedDataFromOptimizer(){

		var ajaxData = [];
		ajaxData[0] = window.bidit_globals.g_allSemestersAccordions[window.bidit_globals.g_currSemester] ;
		ajaxData[1] = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester];


		openBlockUI();
		window.bidit_globals.g_ajaxMiddleShown = false;


		setInterval(function() {   //calls click event after a certain time
			if (window.bidit_globals.g_ajaxMiddleShown==false) {
				showMoreTimeNeeded();
			
				window.bidit_globals.g_ajaxMiddleShown = true;
			}
		}, 20000);


		window.bidit_globals.g_ajaxStopMessage = "לא ניתן להשלים את הבניה האוטומטית. נסה להפחית במספר הקורסים והאילוצים";

		requestAjax = $.ajax({
			type: "POST",
			url: "/ajax/optimizer/",
			timeout: 59000,
			dataType: 'json', 
			data: JSON.stringify(ajaxData),
			complete: function () {
				window.bidit_globals.g_ajaxMiddleShown = true;
				closeBlockUI();

			},

			error: function () {
				/*if optimizer returns no course goes here*/
				
				showAlert(window.bidit_globals.g_ajaxStopMessage,'danger');
				window.bidit_globals.g_ajaxMiddleShown = true;
	
				closeBlockUI();
			}

			
		});
		return requestAjax;
	}

	function showMoreTimeNeeded(){

		$('#wait').css("width","120px");
		$('#wait').css("top","15%");
		$('#wait').css("left","15%");

		openBlockUIBig();
		$('#waitMoreP').removeClass('hide');

	}	

	function hideMoreTimeNeeded(){
		
		$('#wait').css("width","69px");
		$('#wait').css("top","20%");
		$('#wait').css("left","22%");
		$('#waitMoreP').addClass('hide');

	}	

	function makeTroublePrint(input){
		var len = input.length;
		var retStr = '';
		if (len==1) return input;
		for (var i=0 ; i<len-1 ; i++){
			retStr += "'" + input[i] + "', ";
		}
		retStr += "'" + input[len-1] + "', ";
		return retStr;
	}

	function updateSchedualWithOptimizedData(optimizedSched){
		var currSemester = window.bidit_globals.g_currSemester;
		InitSchedualDisplay();

		var optCoursesArr = optimizedSched.optimizedSchedual;

		/*case of empty array, a general message*/
		if(optCoursesArr.length == 0) {
			var mPriority = 'error';
			var messageToShow = 'לא נמצאה מערכת המתאימה לאילוצים שהגדרת.';
			showAlert(messageToShow,mPriority);
			return;
		}
		/*case mustHave course colides with another restriction*/
		if(optCoursesArr[0]==0){
			var trouble = "'"+optCoursesArr[1]+"'";
			var mPriority = 'error';
			var messageToShow = 'לא ניתן להרכיב מערכת כי הקורס '+trouble+' מתנגש עם האילוצים שהזנת.';
			showAlert(messageToShow,mPriority);
			return;
		}

		/*case mustHave courses colide by exam gap*/
		if(optCoursesArr[0]==1){
			var trouble = makeTroublePrint(optCoursesArr[1]);
			var mPriority = 'error';
			var messageToShow = 'אין אפשרות לקחת את קורסים '+trouble+' עקב התנגשות במבחניהם.';
			showAlert(messageToShow,mPriority);
			return;
		}

		/*case mustHave courses colide overlapping hours*/
		if(optCoursesArr[0]==2){
			var trouble = makeTroublePrint(optCoursesArr[1]);
			var mPriority = 'error';
			var messageToShow = 'אין אפשרות לקחת את הקורסים '+trouble+' עקב חפיפה בשעות הלימוד.';
			showAlert(messageToShow,mPriority);
			return;
		}

		else {
			/*case of success*/
			if(optCoursesArr.length > 0){

				//Update global array of display settings
				for(var i=0; i < optCoursesArr.length; i++){
					var currCourseNum = optCoursesArr[i].cNum;
					var currGroupNum = optCoursesArr[i].gNum;
					var havuraNum = ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[currCourseNum]).groups[currGroupNum].havura;
					var currGroupElement = $('li[name="'+ currCourseNum + currGroupNum +'"]');

					// Change display on screen
					changeCourseDisplayOnAccordion(currGroupElement,currCourseNum,0,currGroupNum,false);
				}
				/*update exams and calendar*/
				updateExamsAndCalendar();

				var mPriority = 'warning';
				var messageToShow = 'בניית המערכת הסתיימה, כעת באפשרותך לבצע שינויים.';
				showAlert(messageToShow,mPriority);
				return;
			}
			else{
				/*case of general message, shouldn't get here*/
				var mPriority = 'error';
				var messageToShow = 'לא נמצאה מערכת המתאימה לאילוצים שהגדרת.';
				showAlert(messageToShow,mPriority);
				return;
			}
		}
	}



	$('#mustHaveCourses').delegate('#course', 'click', function() {

		var courseNum = $(this).closest('tr').attr("id");

		// Gets course' element current class
		var tdClassName = $(this).closest('tr').attr("class");
		if(tdClassName == 'must-have-course-cell-hover'){
			// Updates current class of course' cell: chosen or nor chosen
			$(this).closest('tr').removeClass('must-have-course-cell-hover');
			$(this).closest('tr').addClass('depart-cell-highlight');

			//Adds the chosen course to the chosen courses list (on screen and global array)

			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mustHaveCourses"].push(courseNum);

		}
		else{
			// Updates current class of course' cell: chosen or nor chosen
			$(this).closest('tr').removeClass('depart-cell-highlight');
			$(this).closest('tr').addClass('must-have-course-cell-hover');

			delete window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mustHaveCourses"][window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mustHaveCourses"].indexOf(courseNum)];





		}

	});

	/*getting information from optimizer settings by the user*/
	function getOptimizerSettingsFromForm(){
		//var daysOff = document.forms[0].daysOffForm;
		if ($('input[id=maxDays]').val()!=''){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxDays"] = $('input[id=maxDays]').val();
		}

		if ($('input[id=afterHour]').val()!=''){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["minHour"] = $('input[id=afterHour]').val().toString();
		}

		if ($('input[id=beforeHour]').val()!=''){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxHour"] = $('input[id=beforeHour]').val().toString();
		}

		if ($('input[id=examsGap]').val()!=''){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["examsGap"] = $('input[id=examsGap]').val();
		}



	}


	$('#dropDownDays > li').click(function(event){
		event.stopPropagation();
	});

	$('#dropDownDays > li > input').click(function(event){
		selectDay(this.id);
		changeHeadingDays();
	});

	function selectDay(num){

		/*in case not chosen*/
		if (window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester][parseNumToDayOff(num)]==false){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester][parseNumToDayOff(num)]=true;
			changeImageByDayOff(num,true);

			return;
		}
		/*in case chosen*/
		else if (window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester][parseNumToDayOff(num)]==true){
			window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester][parseNumToDayOff(num)]=false;
			changeImageByDayOff(num,false);
			return;
		}


	};

	function changeImageByDayOff(num,status){
		var dayCheck = parseNumToDayOff(num).substring(0,parseNumToDayOff(num).length-3) + 'Check';

		if (status == true){
			$("#"+dayCheck).attr('src',function(i,e){
				return e.replace("lite-blue-empty.png","lite-blue-checked.png");
			})
		}
		else {
			$("#"+dayCheck).attr('src',function(i,e){
				return e.replace("lite-blue-checked.png","lite-blue-empty.png");
			})
		}


	}

	function changeHeadingDays(){
		var daysString = '';
		for(var i=1 ; i<7 ; i++){
			if (window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester][(parseNumToDayOff("dayOff"+i))]==true)	{
				if (daysString=='') {
					daysString += parseDayOffToDay("dayOff"+i)
				}
				else {
					daysString += ", "+parseDayOffToDay("dayOff"+i)
				}

			}
		}


		/*for text to be same sized*/

		if (daysString == "") {
			$('#selectDaysButton').empty();
			$('#selectDaysButton').append( 
			'בחר ימים<span class="caret"></span>');
		}
		else {
			$('#selectDaysButton').empty();
			$('#selectDaysButton').text(daysString);
		}
	}

	function parseNumToDayOff(num){
		switch (num) {
		case ("dayOff1"):
			return "sundayOff";
		break;
		case ("dayOff2"):
			return "mondayOff";
		break;
		case ("dayOff3"):
			return "tuesdayOff";
		break;
		case ("dayOff4"):
			return "wednesdayOff";
		break;
		case ("dayOff5"):
			return "thursdayOff";
		break;
		case ("dayOff6"):
			return "fridayOff";
		break;
		}	

	}

	function parseDayOffToDay(d){
		switch (d) {
		case ("dayOff1"):
			return "א";
		break;
		case ("dayOff2"):
			return "ב";
		break;
		case ("dayOff3"):
			return "ג";
		break;
		case ("dayOff4"):
			return "ד";
		break;
		case ("dayOff5"):
			return "ה";
		break;
		case ("dayOff6"):
			return "ו";
		break;
		}	

	}


//	$.xhrPool and $.ajaxSetup are the solution
	$.xhrPool = [];
	$.xhrPool.abortAll = function() {
		$(this).each(function(idx, jqXHR) {
			jqXHR.abort();
		});
		$.xhrPool = [];
	};

	$.ajaxSetup({
		beforeSend: function(jqXHR) {
			$.xhrPool.push(jqXHR);
		},
		complete: function(jqXHR) {
			var index = $.xhrPool.indexOf(jqXHR);
			if (index > -1) {
				$.xhrPool.splice(index, 1);
			}
		}
	});


	$('#cancelAjaxButton').click(function(){
		window.bidit_globals.g_ajaxStopMessage = "בניית המערכת לא הצליחה עקב ביטול משתמש";
		abortAllRequests();
		closeBlockUI();

	});

	function abortAllRequests(){
		requestAjax.abort();	
	}

	function openBlockUI(){

		$.blockUI({ message: $('#wait'), css: { 
			centerX: true,
			centerY: true,
			height: '100',
			width: '100',
			border: 'none', 
			padding: '15px',
			left: '48%',
			backgroundColor: '#000', 
			'-webkit-border-radius': '10px', 
			'-moz-border-radius': '10px', 
			opacity: .8, 
			color: '#fff' 
		}}); 

	};

	function openBlockUIBig(){

		$.blockUI({ message: $('#wait'), css: { 
			centerX: true,
			centerY: true,
			height: '200',
			width: '150',
			border: 'none', 
			padding: '15px',
			left: '43%',
			backgroundColor: '#000', 
			'-webkit-border-radius': '10px', 
			'-moz-border-radius': '10px', 
			opacity: .8, 
			color: '#fff' 
		}}); 

	};

	function closeBlockUI(){
		hideMoreTimeNeeded();
		$.unblockUI();
		clearAndFocusCourseSearch();
	}

	function clearAndFocusCourseSearch(){
		/*clear and focus on course manual search every time after blockUI*/
		$("#search").focus();
		$("#search").val('');
	}

	$('#helpOptimizer').popover({ placement: 'right',html:true, 
		content: '<br/><br/>בחר את העדפותיך האישיות: כל מאפיין מוגדר לערך ברירת המחדל.<br/>במעבר על כל מאפיין יוצג הסבר.<br/>לחץ על "סגור" לביטול.' });


	$('#helpOptimizer').click(function(){
		if (window.bidit_globals.g_helpOptimize == false){
			showHelpOptimizer();
			window.bidit_globals.g_helpOptimize = true;
			$('#helpOptimizer').empty();
			$('#helpOptimizer').append('סגור');


		}
		else {
			hideHelpOptimizer();
			window.bidit_globals.g_helpOptimize = false;
			$('#helpOptimizer').empty();
			$('#helpOptimizer').append('עזרה');
		}

		$('#helpOptimizer').popover('toggle');

	});



	function showHelpOptimizer(){
		$('#maxDaysRow').popover({ placement: 'right', trigger: 'hover', 
			content: 'סמן את מספר הימים המקסימלי בשבוע שתרצה ללמוד' });
		$('#daysOffRow').popover({ placement: 'right', trigger: 'hover', 
			content: 'סמן את ימי החופש שתרצה במהלך השבוע' });
		$('#afterHourRow').popover({ placement: 'right', trigger: 'hover', 
			content: 'סמן את השעה המוקדמת ביותר שתרצה ללמוד' });
		$('#beforeHourRow').popover({ placement: 'right', trigger: 'hover', 
			content: 'סמן את השעה המאוחרת ביותר שתרצה ללמוד' });
		$('#examsGapRow').popover({ placement: 'right', trigger: 'hover', 
			content: 'סמן את המרווח המינימלי בין תאריכי מבחנים שתרצה' });
		$('#mustHaveCoursesRow').popover({ placement: 'left', trigger:'hover', 
			content: 'קורסים שאתה מתכוון לקחת בכל מקרה. לחץ על קורס לסימון.' });



	}

	function hideHelpOptimizer(){
		$('#maxDaysRow').popover('destroy');
		$('#daysOffRow').popover('destroy');
		$('#afterHourRow').popover('destroy');
		$('#beforeHourRow').popover('destroy');
		$('#examsGapRow').popover('destroy');
		$('#mustHaveCoursesRow').popover('destroy');

	}		



	/*================================================================================================
	 *                                       Build Time Table Screen (Main Screen)
	 *================================================================================================
	 */

	/*gets an hour in the format of 2.75 and returns 2:45*/
	function formatTotalHours(hourFromServer){
		var fHourFromServer = parseFloat(hourFromServer);
		var totalHours = parseInt(fHourFromServer);
		var totalMinutes = parseInt((fHourFromServer - totalHours) * 60);

		return (totalHours.toString() + ':' + totalMinutes.toString());
	}

	function getHavuraNum(strHavuraLetter){
		var asciiNum = strHavuraLetter.charCodeAt(0);
		var havuraNum = asciiNum - 64;
		return havuraNum;
	}

	function getDayNum(strDay){
		switch (strDay) {
		case ('א'):
			return 0;
		break;
		case ('ב'):
			return 1;
		break;
		case ('ג'):
			return 2;
		break;
		case ('ד'):
			return 3;
		break;
		case ('ה'):
			return 4;
		break;
		case ('ו'):
			return 5;
		break;
		default:
			return -1;
		}
	}


	function getHour(strTime){
		return strTime.substr(0,2);	
	}

	function getMinutes(strTime){
		return strTime.substr(3,2);	
	}

	function InitSchedualDisplay(){

		var currSemester = window.bidit_globals.g_currSemester;
		var accordionArr = window.bidit_globals.g_allSemestersAccordions[currSemester];
		window.bidit_globals.g_schedulesArr[currSemester] = new Array();
		clearTimetableView();

		//Init total hours
		window.bidit_globals.g_totalHoursArr[currSemester] = '0';
		window.bidit_globals.g_totalZchutHoursArr[currSemester] = 0.0;
		
		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

		//Init display settings array
		for(var i=0; i<accordionArr.length; i++){
			var courseNum = accordionArr[i].cNum;
			(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cChosen = false;
			
			(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].chosenGroups = 0;

			var courseColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cColor; 
			if(courseColor != 'white'){
				window.bidit_globals.g_scheduleColors.splice(window.bidit_globals.g_scheduleColors.indexOf(courseColor),1);
				window.bidit_globals.g_colorsStock.push(courseColor);
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].cColor = 'white';
			}
			var groupsArr = accordionArr[i].kvutzaData;
			for(var j=0; j<groupsArr.length; j++){
				var groupNum = groupsArr[j].gNum;
				var isGroupChosen = ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum]).groups[groupNum].gChosen;
				if(isGroupChosen){
					var currGroupElement = $('li[name="'+ courseNum + groupNum +'"]');
					currGroupElement.removeClass('course-cell-highlight');
					currGroupElement.addClass('course-cell-hover');
					((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum]).groups[groupNum].gChosen = false;
				}

				$('#'+courseNum).css({'background-color': 'white'});
			}
		}

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

		/*update exams and calendar*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/
		clearAndFocusCourseSearch();
	}

	// The function emptys the main screen and shows the current courses and schedual
	// Uses the SemesterSwitch function and the loadSchedule function 
	function showCurrentCoursesAndSchedule(){
		var currSemester = window.bidit_globals.g_currSemester;
		//Deleting previous semester information from main screen
		$('#accordion2').empty();
		clearTimetableView();		

		//Updating current semester info on main screen 
		var currAccordion = window.bidit_globals.g_allSemestersAccordions[currSemester];
		var displaySettings = window.bidit_globals.g_coursesDisplaySettings[currSemester];
		var MAIN_STR = 'ראשית';
		var SUB_STR = 'משנית';
		var OPTION_STR = 'אפשרות';

		// Creating accordion's html tags
		$.each(currAccordion,function(){
			var courseName = this.cName;
			var groupsArr = this.kvutzaData;
			var currCourseNum = this.cNum;
			var courseHeading = this.cName + ' (' + this.cNum + ')';
			var numOfHavurot = this.havurotNum; 
			buildMainCoursesAccordion(currCourseNum,numOfHavurot,OPTION_STR,courseHeading);

			/* Iterates over the groups of one course */
			$.each(groupsArr,function(){
				var gKind = this.kind;
				var gHavura = getHavuraNum(this.havura);
				var gNum = this.gNum;
				var gLecturer = this.lecturer;
				var gOfenHoraa = this.ofenHoraa;

				if(gKind == MAIN_STR){
					addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gOfenHoraa, gHavura, 'main');
				}
				else if(gKind == SUB_STR){
					addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gOfenHoraa, gHavura, 'sub');
					$('#subBorder' + currCourseNum + gHavura).show();
				}
			});
		});

		// Updating group selections on main accordion
		$.each(displaySettings, function(){
			var cNum = this.cNum;
			var cColor = this.cColor;
			var courseObj = displaySettings[cNum];
			if(courseObj.cChosen == true){
				//Change chosen course color
				$('#'+cNum).css('background-color',cColor);	

				//Iterating over current course's groups
				$.each(courseObj.groups, function(){
					if(this.gChosen == true){
						var currGroupElement = $('li[name="'+ cNum + this.gNum +'"]');
						currGroupElement.removeClass('course-cell-hover');
						currGroupElement.addClass('course-cell-highlight');
					}
				});
			}
		});

		// Updating group selections on schedule
		updateTimeTableView();

		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/
		clearAndFocusCourseSearch();
	}


	function saveCourseCatalogDetails(){
		// save course catalog modal datails for current semester
		var tempChosenCoursesNumbers= window.bidit_globals.g_newChosenCoursesArr;
		var catalog_modal_datails_semester = {'cfacultynum':window.bidit_globals.g_currChosenFacultyNum,'cfacultyname':window.bidit_globals.g_currChosenFacultyName,'cdepartnum':window.bidit_globals.g_currChosenDepart,'cdepartname':window.bidit_globals.g_currChosenDepartName,'cday':window.bidit_globals.g_currChosenDayNum,'ccoursenums':window.bidit_globals.g_newChosenCoursesArr};
		if(window.bidit_globals.g_currSemester==0){

			localStorage.setItem('catalog_modal_details_semestera',JSON.stringify(catalog_modal_datails_semester));


		}
		else{
			localStorage.setItem('catalog_modal_details_semesterb',JSON.stringify(catalog_modal_datails_semester));

		}

	}

	/* The user switched the schedule to another semester.
	 * This function Updates all screens according to the current semester */
	function SemestersSwitch(){
		/*karin: changing courses in auto-complete to the relevant semester - for now always dynamic*/
		initAutoComplete();


		//Changing faculties and departments list on course catalog screen
		$('#filters-accordion').empty();
		$('#filters-accordion-2').empty();
		$('#courseTable').empty();
		$('#dropdownFacultiesList').empty();
		getFacultiesAndDepartsFromAjax();

		//Updates all the courses and schedule on main screen
		showCurrentCoursesAndSchedule();

		//Initializing globals
		window.bidit_globals.g_currCourseProfile = '-1';
		window.bidit_globals.g_currChosenDepart = 'NOT_CHOSEN';
		window.bidit_globals.g_currChosenInfoBtnDepart = 'NOT_CHOSEN';
		window.bidit_globals.g_currChosenDepartName = '';
		window.bidit_globals.g_currChosenFacultyName = '';
		window.bidit_globals.g_currChosenFacultyNum = '';
		window.bidit_globals.g_currCourseInfo = [];
		window.bidit_globals.g_currCourseUploaded = false;
		window.bidit_globals.g_toSaveSelection = false;
		window.bidit_globals.g_isProfileOpenedFromMain = true;
		window.bidit_globals.g_jsonOptimizer = [];
		window.bidit_globals.g_newChosenCoursesArr = [];

		resetOptimizeDateToCurrSemester(window.bidit_globals.g_currSemester);

		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/
		clearAndFocusCourseSearch();

		localStorage.currSemesterStored = window.bidit_globals.g_currSemester;

	}


	/* delete course from data structure in the other semester before we move to the other semester */
	function deleteFromDataStructAnotherSem(cNum,groupNums,semester){
		var currCourseObj =  (window.bidit_globals.g_coursesDisplaySettings[semester])[cNum];
		var courseColor = currCourseObj.cColor;
		
		$.each(currCourseObj.groups,function(){
			var currGroupObj = this;
			if(currGroupObj.gChosen){
				UpdateTotalHours(semester,currGroupObj,'remove',false,false);
			}
		});
		
		if(currCourseObj.cChosen){
			UpdateZchutHours(semester,currCourseObj,'remove',false,false);
		}
		
		 
		if(courseColor != 'white'){
			var colorIndex = window.bidit_globals.g_scheduleColors.indexOf(courseColor);
			if(colorIndex != -1){
				window.bidit_globals.g_scheduleColors.splice(colorIndex,1);
				window.bidit_globals.g_colorsStock.push(courseColor);
			}
		}
		
		$.each(groupNums,function(){
			var gNum = this;

			//Deleting course classes("mifgashim") from schedual arr
			removeGroupFromScheduleArray(semester,cNum,gNum);
			
		});

		removeCourseFromDataStructuresHelper(semester, cNum);	
		
	}
	

	function needToBeDel(num,currSem,otherSem){
		var otherSemCourses = window.bidit_globals.g_allSemestersAccordions[otherSem];

		var answer = true;
		$.each(otherSemCourses,function(){
			if (this.cNum == num){
				answer = false;
			}

		});
		
		return answer;
	}



	function resetOptimizeDateToCurrSemester(semester){
		$('#mustHaveTable > tbody > tr').each(function(){
			var courseNum = $(this).attr("id");

			var index = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mustHaveCourses"].indexOf(courseNum);

			/*in case the course already chosen as MustHave*/

			if (index > -1){

				$(this).removeClass('must-have-course-cell-hover');
				$(this).addClass('depart-cell-highlight');

				//Adds the chosen course to the chosen courses list (on screen and global array)


			}
		})

		/*reset optimizer*/
		$('#maxDaysArea').empty();
		$('#afterHourArea').empty();
		$('#beforeHourArea').empty();
		$('#examsGapArea').empty();

		$('#selectDaysButton').empty();

		$('#maxDaysArea').append('<input id="maxDays" type="number" min="1" style="text-align: center" max="6" step="1" class="input-smallMedium" value="'+window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxDays"]+'"/>');

	
		document.getElementById("dayOff1").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["sundayOff"];
		document.getElementById("dayOff2").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mondayOff"];
		document.getElementById("dayOff3").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["tuesdayOff"];
		document.getElementById("dayOff4").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["wednesdayOff"];
		document.getElementById("dayOff5").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["thursdayOff"];
		document.getElementById("dayOff6").checked = window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["fridayOff"];


		var daysCheck = ["#sundayCheck","#mondayCheck","#tuesdayCheck","#wednesdayCheck","#thursdayCheck","#fridayCheck"]

		for (var i=1 ; i<7 ; i++){
			if (document.getElementById("dayOff"+i).checked)
				$(daysCheck[i-1]).attr('src',"assets/img/lite-blue-checked.png");
			else
				$(daysCheck[i-1]).attr('src',"assets/img/lite-blue-empty.png");
		}

		changeHeadingDays();

		$('#afterHourArea').append('<input id="afterHour" type="time" style="text-align: center" class="input-smallMedium " min="08:00:00" max="22:00:00" value="'+window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["minHour"]+'"/>');

		$('#beforeHourArea').append('<input id="beforeHour" type="time" style="text-align: center" class="input-smallMedium" min="08:00:00" max="22:00:00" value="'+window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxHour"]+'"/>');

		$('#examsGapArea').append('<input id="examsGap" type="number" min="0" style="text-align: center" step="1" class="input-smallMedium" value="'+window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["examsGap"]+'"/>');

	}




	function resetOptimizeDate(){
		/*reset data*/
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxDays"]=6;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["sundayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mondayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["tuesdayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["wednesdayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["thursdayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["fridayOff"]=false;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["minHour"]="08:00";
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["maxHour"]="22:00";
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["examsGap"]=0;
		window.bidit_globals.g_optimizeData[window.bidit_globals.g_currSemester]["mustHaveCourses"]=[];

		/*reset optimizer*/
		$('#maxDaysArea').empty();
		$('#afterHourArea').empty();
		$('#beforeHourArea').empty();
		$('#examsGapArea').empty();

		$('#selectDaysButton').empty();

		$('#maxDaysArea').append('<input id="maxDays" type="number" min="1" style="text-align: center" max="6" step="1" class="input-mini" value="6"/>');

		document.getElementById("dayOff1").checked = false;
		document.getElementById("dayOff2").checked = false;
		document.getElementById("dayOff3").checked = false;
		document.getElementById("dayOff4").checked = false;
		document.getElementById("dayOff5").checked = false;
		document.getElementById("dayOff6").checked = false;

		$("#sundayCheck").attr('src',"assets/img/lite-blue-empty.png");
		$("#mondayCheck").attr('src',"assets/img/lite-blue-empty.png");
		$("#tuesdayCheck").attr('src',"assets/img/lite-blue-empty.png");
		$("#wednesdayCheck").attr('src',"assets/img/lite-blue-empty.png");
		$("#thursdayCheck").attr('src',"assets/img/lite-blue-empty.png");
		$("#fridayCheck").attr('src',"assets/img/lite-blue-empty.png");

		changeHeadingDays();


		$('#afterHourArea').append('<input id="afterHour" type="time" style="text-align: center"  class="input-mini" value="08:00"/>');

		$('#beforeHourArea').append('<input id="beforeHour" type="time"  style="text-align: center" class="input-mini" value="22:00"/>');

		$('#examsGapArea').append('<input id="examsGap" type="number" min="0" style="text-align: center" step="1" class="input-mini" value="0"/>');
	}


	/* The actual semester switching - the user clicked on a semester tab */
	$('#semesterA').click(function(){
		if(window.bidit_globals.g_currSemester != 0){
			window.bidit_globals.g_currSemester = 0;
			SemestersSwitch();
			$('#CatalogModalLabel').text("בחר קורסים והוסף למערכת (סמסטר א')");


		}

		/*if there are courses show the optimizer button*/
		showOrHideOptimizeButton();
		window.bidit_globals.g_viaLcalStorage = false;

	});


	$('#semesterB').click(function(){
		if(window.bidit_globals.g_currSemester != 1){
			window.bidit_globals.g_currSemester = 1;
			SemestersSwitch();
			$('#CatalogModalLabel').text("בחר קורסים והוסף למערכת (סמסטר ב')");
		}

		/*if there are courses show the optimizer button*/
		showOrHideOptimizeButton();
		window.bidit_globals.g_viaLcalStorage = false;


	});

	/* Checks if all groups of specific havura are chosen */
	function isAllHavuraChosen(courseNum,havuraNum){
		var currSemester = window.bidit_globals.g_currSemester;
		var isAllChosen = true;
		var groupsArr = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNum].groups;
		$.each(groupsArr, function(){
			if(this.gChosen == false && havuraNum == this.havura){
				isAllChosen = false;
				return isAllChosen;
			}
		});

		return isAllChosen;
	}

	function buildMainCoursesAccordion(currCourseNum,numOfHavurot,OPTION_STR,courseHeading){
		// each accordion group has 2 ids: "lec-{courseNum}" for lectures list, "rec-{courseNum}" for recitations list  
		$('<div id="'+ currCourseNum +'" name="ag' + currCourseNum + '" class="accordion-group">'+
				'<div class="accordion-heading row-fluid">' +
				'<div id="'+ currCourseNum + '" class="span1"><a id="mChosenCourseRemove" data-parent="#accordion2"><i class="course-action-hover icon-remove"></i></a></div>' +
				'<div id="'+ currCourseNum + '" class="span1"><a id="mInfoBtn" data-parent="#accordion2"><i class="course-action-hover icon-info-sign"></i></a></div>' +
				'<div class="span8 offset2"><a class="accordion-toggle" id="accTog'+currCourseNum+'" data-toggle="collapse" data-parent="#accordion2" href="#collapse'+ currCourseNum + '">'+ courseHeading +'</a></div>'+
				'</div>'+
				'<div  id="collapse' + currCourseNum + '" class="accordion-body collapse">'+
				'<div class="accordion-inner" id="inner' + currCourseNum + '">').appendTo('#accordion2');

		// Creates number of options for course ("havurot")
		// Each course option will have the id: lec\rec-{course number)-{havura}
		for (var i = 1; i <= numOfHavurot; i++){
			$('<div><div class="bidit-pre" id="havura-' + currCourseNum + i + '" style="margin-bottom:2px;"><div id="course-option" style="margin:1px;"><b>' + OPTION_STR + ' ' + i + '</b></div>' +
					'<ul class="unstyled" id="main-' + currCourseNum + '-' + i + '" style="margin-bottom:0px;">' +			
					'</ul>'+
					'<div id="subBorder'+ currCourseNum  + i +'" style="margin-top:0px;"><div style="border-bottom: 2px solid #dddddd; margin-top:2px;"></div><div style="margin-top:2px;"></div></div>' + 
					'<ul class="unstyled" id="sub-' + currCourseNum + '-' + i + '" style="margin:0px;">' +
			'</ul></div></div>').appendTo('#inner' + currCourseNum);

			$('#subBorder' + currCourseNum + i).hide();

		}

		$('</div>' +
		'</div></div>').appendTo('#accordion2');


	}

	function addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gOfenHoraa, gHavura, strMainOrSub){
		var lecturerName = '';
		if(gLecturer[0] == undefined){
			lecturerName = '<b><i>המידע לא זמין</i></b>';
		}
		else{
			lecturerName = gLecturer[0];
		}
		if(gOfenHoraa == undefined){
			gOfenHoraa = '';
		}
		else{
			gOfenHoraa = ' (' + gOfenHoraa + ') '
		}

		$('<li name="'+ currCourseNum + gNum +'" id="' + currCourseNum + '" title="' + gNum + '" class="courseGroup course-cell-hover" unstyled">'+
				  
				'<span>' + gNum + ": " + lecturerName + gOfenHoraa + '</span>' + 
				
		'</li>').appendTo('#' + strMainOrSub + '-' + currCourseNum + '-' + gHavura);
	}

	function createCourseObj(isCourseChosen, currCourseNum, courseName, chosenGroupsNum, courseColor, courseZchutHours, groupsObj, moedType, moed, startMoedHours, endMoedHours, dates){
		var funcCourseObj = {};

		funcCourseObj['cChosen'] = isCourseChosen;
		funcCourseObj['cNum'] = currCourseNum;
		funcCourseObj['cName'] = courseName;
		funcCourseObj['chosenGroups'] = chosenGroupsNum;
		funcCourseObj['cColor'] = courseColor;
		funcCourseObj['cZchutHours'] = courseZchutHours;
		funcCourseObj['groups'] = groupsObj;

		funcCourseObj['types'] = moedType;
		funcCourseObj['moeds'] = moed;
		funcCourseObj['startMoedHours'] = startMoedHours;
		funcCourseObj['endMoedHours'] = endMoedHours;
		funcCourseObj['dates'] = dates;

		return funcCourseObj;
	}

	function createGroupObj(gNum, isGroupChosen, gHavura, startHours, endHours, days, places, gOfenHoraa, gHours, gKind){
		var funcGroupObj = {};
		var MAIN_STR = 'ראשית';
		var SUB_STR = 'משנית';

		funcGroupObj['gNum'] = gNum;
		funcGroupObj['gChosen'] = isGroupChosen;
		funcGroupObj['havura'] = gHavura;
		funcGroupObj['startHours'] = startHours;
		funcGroupObj['endHours'] = endHours;
		funcGroupObj['daysArr'] = days;


		funcGroupObj['places'] = places;
		funcGroupObj['ofenHoraa'] = gOfenHoraa;
		funcGroupObj['gHours'] = gHours;

		if(gKind == MAIN_STR){
			funcGroupObj['kind'] = 'main';
		}
		else if(gKind == SUB_STR){
			funcGroupObj['kind'] = 'sub';
		}

		return funcGroupObj;
	}

	function addCoursesToMain(leng, semesterNum){
		var currSemester = window.bidit_globals.g_currSemester;
		var otherSemester = getOtherSemester(currSemester);
		var isGivenCurrSemester = (currSemester == semesterNum);

		var currAccordion = window.bidit_globals.g_allSemestersAccordions[semesterNum]; /*after the new added*/
		var MAIN_STR = 'ראשית';
		var SUB_STR = 'משנית';
		var OPTION_STR = 'אפשרות';
		var toOpenFirst = false;

		/* in case this is the first additions of courses */
		if (currAccordion.length - leng == 0 && currAccordion.length > 0){
			openFirstAccordion(currAccordion);
		}

		$.each(currAccordion,function(){

			if(window.bidit_globals.g_chosenCoursesArr[semesterNum].indexOf(this.cNum) == -1){

				//Course Data
				var groupsArr = this.kvutzaData;
				var currCourseNum = this.cNum;
				var courseHeading = this.cName + ' (' + this.cNum + ')';
				var numOfHavurot = this.havurotNum; 
				var courseName = this.cName;
				var courseZchutHours = this.zchutHours;

				//Tests Data
				var moed = this.kvutzaData[0].moed;
				var moedType = this.kvutzaData[0].moedType;
				var startMoedHours = this.kvutzaData[0].startMoedHours;
				var endMoedHours = this.kvutzaData[0].endMoedHours;
				var dates = this.kvutzaData[0].dates;

				// Adding the new chosen courses from the server to the global courses array
				window.bidit_globals.g_chosenCoursesArr[semesterNum].push(currCourseNum);

				// (Display Settings) Initalizing and adding new course display object to global display array
				var courseObj = {};
				courseObj = createCourseObj(false, currCourseNum, courseName, 0, 'white', courseZchutHours, {}, moedType, moed, startMoedHours, endMoedHours, dates);

				if(isGivenCurrSemester){
					buildMainCoursesAccordion(currCourseNum,numOfHavurot,OPTION_STR,courseHeading);	
				}


				/* Iterates over the groups of one course */
				$.each(groupsArr,function(){
					var gKind = this.kind;
					var gHavura = getHavuraNum(this.havura);
					var gNum = this.gNum;
					var gLecturer = this.lecturer;
					var gOfenHoraa = this.ofenHoraa;
					var days = this.days;
					var startHours = this.beginHours;
					var endHours = this.endHours;
					var places = this.place;
					var gHours = formatTotalHours(this.amountHours);

					// (Display Settings)
					var groupObj = {};

					if(isGivenCurrSemester){
						if(gKind == MAIN_STR){
							addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gOfenHoraa, gHavura, 'main');
						}
						else if(gKind == SUB_STR){
							addGroupsToMainAccordion(currCourseNum, gNum, gLecturer, gOfenHoraa, gHavura, 'sub');

							$('#subBorder' + currCourseNum + gHavura).show();
						}	
					}

					groupObj = createGroupObj(gNum, false, gHavura, startHours, endHours, days, places, gOfenHoraa, gHours, gKind);

					// (Display Settings)
					courseObj.groups[gNum.toString()] = groupObj;

				});

				// (Display Settings)
				(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[currCourseNum.toString()] = courseObj;

			}
		});

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);


		/*if there are courses show the optimizer button*/
		showOrHideOptimizeButton();

	}



	/* The user clicked on a course's group */
	$('#accordion2').delegate('.courseGroup', 'click', function() {
		var chosenGroup = $(this);
		var chosenGroupNum =  chosenGroup.attr('title');
		var chosenCourseNum = chosenGroup.attr('id');

		var currSemester = window.bidit_globals.g_currSemester;
		var courseIndex = window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(chosenCourseNum);

		changeCourseDisplayOnAccordion(chosenGroup,chosenCourseNum,courseIndex,chosenGroupNum,true);


		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();

		/*clear and foucs on course search*/

	});

	function UpdateTotalHours(currSemester,currGroupObj,op,isGroupClicked,isCurrentSemester){
		// Update total hours of courses in schedual
		var tmpHours = parseInt(currGroupObj.gHours.substring(0, currGroupObj.gHours.indexOf(':')));
		var tmpMinutes = parseInt(currGroupObj.gHours.substring(currGroupObj.gHours.indexOf(':')+1,currGroupObj.gHours.length));


		var gTotalHours = window.bidit_globals.g_totalHoursArr[currSemester];
		var currHours = 0;
		var currMinutes = 0;
		if(gTotalHours.indexOf(':') != -1){
			currHours = parseInt(gTotalHours.substring(0, gTotalHours.indexOf(':')));
			currMinutes = parseInt(gTotalHours.substring(gTotalHours.indexOf(':')+1,gTotalHours.length));
		}
		else{
			currHours = gTotalHours;
		}
		var currTotalMinutes = currHours*60 + currMinutes;
		var tmpTotalMinutes = tmpHours*60 + tmpMinutes;
		var minutesToAdd = 0;
		var hoursToAdd = 0;
		if(op == 'add'){			
			minutesToAdd = Math.round((currTotalMinutes + tmpTotalMinutes)%60);
			hoursToAdd = parseInt((currTotalMinutes + tmpTotalMinutes)/60);

		}
		else if(op == 'remove'){
			minutesToAdd = Math.round((currTotalMinutes - tmpTotalMinutes)%60);
			hoursToAdd = parseInt((currTotalMinutes - tmpTotalMinutes)/60);
		}


		if(minutesToAdd == 0){
			window.bidit_globals.g_totalHoursArr[currSemester] =  hoursToAdd.toString();
		}
		else{
			window.bidit_globals.g_totalHoursArr[currSemester] = hoursToAdd + ':' + minutesToAdd;		
		}

		if(isCurrentSemester){
			$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);	
		}
		

	}

	function UpdateZchutHours(currSemester,currCourseObj,op,isCurrentSemester){
		if(op == 'add'){
			window.bidit_globals.g_totalZchutHoursArr[currSemester] = window.bidit_globals.g_totalZchutHoursArr[currSemester] + parseFloat(currCourseObj.cZchutHours);

		}
		else if(op == 'remove'){
			window.bidit_globals.g_totalZchutHoursArr[currSemester] = window.bidit_globals.g_totalZchutHoursArr[currSemester] - parseFloat(currCourseObj.cZchutHours);

		}
		
		if(isCurrentSemester){
			$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);	
		}
		
	}

	/* The user clicked on a course's group */
	function changeCourseDisplayOnAccordion(courseGroupElem,courseNum,courseIndex,courseGroupNum,isGroupClicked){

		var currSemester = window.bidit_globals.g_currSemester;
		var courseNumStr = courseNum.toString();
		var groupNumStr = courseGroupNum.toString();
		var currCourseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr];
		var currGroupObj = currCourseObj.groups[groupNumStr];

		//Check if course is Yearly

		var startHours = currGroupObj.startHours;
		var endHours = currGroupObj.endHours;
		var daysArr = currGroupObj.daysArr;
		var placesArr = currGroupObj.places;
		var groupOptionNum = currGroupObj.havura;

		var colorArr = window.bidit_globals.g_colorsStock;
		//Checks if this group has already been chosen, saves a boolean
		var isGroupChosen = currGroupObj.gChosen;

		//Checks if the user already chose a group from this course, saves a boolean
		var isCourseChosen = currCourseObj.cChosen;
		var gKind = currGroupObj.kind;


		// If group not chosen - Colors the chosen group of the specific course 
		if(!isGroupChosen){

			// Update total hours of courses in schedual
			var tmpHours = parseInt(currGroupObj.gHours.substring(0, currGroupObj.gHours.indexOf(':')));
			var tmpMinutes = parseInt(currGroupObj.gHours.substring(currGroupObj.gHours.indexOf(':')+1,currGroupObj.gHours.length));
			if(startHours.length == 0 || endHours.length == 0 || daysArr.length == 0 || (tmpHours == 0 && tmpMinutes == 0)){
				if(isGroupClicked){
					showAlert('שים לב: לקבוצה שבחרת לא קיימים מפגשים במערכת', 'error')
				}
			}

			// Check if there is another chosen group of the same course and the same kind
			// If there is one, unchoose it

			// change group to 'chosen'
			courseGroupElem.removeClass('course-cell-hover');
			courseGroupElem.addClass('course-cell-highlight');
			(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].groups[groupNumStr].gChosen = true;
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups)++;

			UpdateTotalHours(currSemester,currGroupObj,'add',isGroupClicked,true);

			// If course not chosen - change the color of the entire course accordion-block
			if(!isCourseChosen){

				//Gets a color from colors array
				var currColor = colorArr.pop();
				window.bidit_globals.g_scheduleColors.push(currColor);
				//Updates chosen course color
				$('#'+courseNum).css({'background-color': currColor});						

				//Save course color
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor = currColor;
				//Change course to chosen on global array
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cChosen = true;

				UpdateZchutHours(currSemester,currCourseObj,'add',true);
			}

			//Add group to be presented on schedule and to the schedule global array
			addGroupToSchedule(currSemester,courseNumStr,groupNumStr,startHours,endHours,daysArr,placesArr);


		}
		// If group is already chosen - uncolors the chosen group of the specific course 
		else{

			courseGroupElem.removeClass('course-cell-highlight');
			courseGroupElem.addClass('course-cell-hover');
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr]).groups[groupNumStr].gChosen = false;
			((window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups)--;

			// Checks if this group was the only group chosen from its course,saves a boolean
			var isOnlyChosenGroup = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].chosenGroups;

			UpdateTotalHours(currSemester,currGroupObj,'remove',isGroupClicked,true);

			// If it was the only one chosen - uncolor the entire course accordion block
			if(isOnlyChosenGroup == 0){

				var currColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor;

				window.bidit_globals.g_scheduleColors.splice(window.bidit_globals.g_scheduleColors.indexOf(currColor),1);
				window.bidit_globals.g_colorsStock.push(currColor);


				$('#'+courseNumStr).css({'background-color': 'white'});
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cColor = 'white';
				(window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr].cChosen = false;

				UpdateZchutHours(currSemester,currCourseObj,'remove',true);
			}

			removeGroupFromSchedule(courseNumStr,groupNumStr);

		}

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
	}



	function clearTimetableView() {
		$(".ttClasses .ttClass").remove();
	}

	function updateTimeTableView(){
		var classesElement = $(".ttClasses");
		var currSemester = window.bidit_globals.g_currSemester;
		var totalHours = 0;

		//Updates depths (for classes conflicts)
		var classes = sortClassesByTime();
		window.bidit_globals.g_schedulesArr[currSemester] = classes;
		depths = UpdateClassesDepth();

		// (2) Adding to schedule table on screen
		var dCounter = -1;

		classesNum = classes.length;

		for(var i=0; i < classesNum; i++){
			var classObj = classes[i];
			var currCourseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[classObj.cNum];
			var currGroupObj = currCourseObj.groups[classObj.gNum];

			//Creates the class text
			var classTextCourse = classObj.gNum + " - " + classObj.cName;
			var classTextSub =  " (" + currGroupObj.ofenHoraa + ") " + classObj.place;
			//Creates the class text

			var isSpecialCollision = false;
			if(depths[i] <= -2){
				isSpecialCollision = true;
				depths[i] = depths[i] / (-2);
			}
			//Init depth counter 
			if (dCounter == -1) {
				dCounter = depths[i];
			}
			//Create class element
			var classElement = $('<div>').addClass("ttClass");
			classElement.attr('id',classObj.cNum);
			classElement.attr('title',classTextCourse + classTextSub);


			$("<div>").addClass("ttClassColor").appendTo($(classElement));

			/*addition so we can change style*/
			var nodeCourse = document.createTextNode(classTextCourse);
			var nodeSub = document.createTextNode(classTextSub);
			var spanCourse = document.createElement('span');
			var spanSub = document.createElement('span');
			var linebreak = document.createElement('br');
			spanCourse.style.fontWeight = "bold";
			spanCourse.style.fontSize = "12px";
			spanSub.style.fontWeight = "lighter";
			spanSub.style.direction = "rtl";
			spanSub.style.textAlign = "right";
			spanSub.style.cssFloat = "right";
			//spanSub.className = "";

			spanCourse.appendChild(nodeCourse);
			spanCourse.appendChild(linebreak);
			spanSub.appendChild(nodeSub);

			classElement.append(spanCourse); /*was*/
			classElement.append(spanSub);
			classElement.css('background-color',currCourseObj.cColor);
			classElement.css('overflow','hidden');
			/*end of addition*/


			try{
				//Position and Size
				var startHour = new Date(2000, 1, 1, classObj.startHour.substr(0,2), classObj.startHour.substr(3,2), 0, 0)
				var endHour = new Date(2000, 1, 1, classObj.endHour.substr(0,2), classObj.endHour.substr(3,2), 0, 0)


				//Top
				var rowName = "#row_" + (startHour.getHours() <= 9 ? "0" + startHour.getHours() : startHour.getHours()) + "00";
				var top = $(rowName).position().top + startHour.getMinutes() * $(rowName).height() / 60;

				//Width
				var width = $("#" + getDayNum(classObj.day) + getHour(classObj.startHour) + "00").outerWidth();
				width = width / (depths[i] + 1);

				//Left
				var left = $("#" + getDayNum(classObj.day) + getHour(classObj.startHour) + "00").position().left + width * (depths[i] - dCounter);

				//Height
				rowName = "#row_" + (endHour.getHours() <= 9 ? "0" + endHour.getHours() : endHour.getHours()) + "00";
				var bottom = $(rowName).position().top + endHour.getMinutes() * $(rowName).height() / 60;
				var height = bottom - top;
				top = top + 2;
				left = left + 1;

				$(classElement).css("left", left + "px");
				$(classElement).css("top", top + "px");
				$(classElement).css("height",height + "px");
				$(classElement).css("width", width + "px");

				$(classElement).appendTo($(classesElement));

				if(depths[i+1] >= 0){
					dCounter--;
				}

			}
			catch(e){
				continue;
			}
		}
	}

	function addGroupToSchedule(semester,courseNumStr,groupNumStr,startHoursArr,endHoursArr,daysArr,placesArr){
		//Clear current courses
		clearTimetableView();

		var currSemester = semester;
		var classesNum = daysArr.length; // Number of 'mifgashim' of this course   
		var courseObj = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[courseNumStr];

		// Adds the class object to schedule array and to schedual table on screen
		// (1) Adding to classes Array
		for(var i=0; i < classesNum; i++){
			var classObj = {}
			classObj['cName'] = courseObj.cName;
			classObj['cNum'] = courseNumStr;
			classObj['gNum'] = groupNumStr;
			classObj['day'] = daysArr[i];
			classObj['startHour'] = startHoursArr[i];
			classObj['endHour'] = endHoursArr[i];
			classObj['place'] = placesArr[i];

			window.bidit_globals.g_schedulesArr[currSemester].push(classObj);

		}

		updateTimeTableView();

	}


	function findCourseIndexInSchedualArr(cNum,gNum,currSemester){
		var schedArr = window.bidit_globals.g_schedulesArr;

		for(var i=0; i<schedArr[currSemester].length; i++){
			if(schedArr[currSemester][i].cNum == cNum && schedArr[currSemester][i].gNum == gNum){
				return i;
			}
		}

		return -1;
	}

	/**
	 * removes groups info from the classes array
	 */
	function removeGroupFromScheduleArray(currSemester,courseNumStr,groupNumStr){

		var isAllRemoved = false;
		while(isAllRemoved == false){
			var cIndex = findCourseIndexInSchedualArr(courseNumStr,groupNumStr,currSemester);
			if(cIndex == -1){
				isAllRemoved = true;
			}
			else{
				window.bidit_globals.g_schedulesArr[currSemester].splice(cIndex,1);
			}	
		}		
	}

	function removeGroupFromSchedule(courseNumStr,groupNumStr){
		//Remove from array
		var currSemester = window.bidit_globals.g_currSemester;

		removeGroupFromScheduleArray(currSemester,courseNumStr,groupNumStr);


		//Remove from screen
		//Clear current courses
		clearTimetableView();
		updateTimeTableView();
	}


	function UpdateClassesDepth(){
		var currSemester = window.bidit_globals.g_currSemester;
		var classesArr = window.bidit_globals.g_schedulesArr[currSemester];

		var depths = new Array();
		var currentDepth = 0;

		depths[0] = 0;

		//analyze depth for each class
		for (var i = 0; i < classesArr.length - 1; i++) {

			var cCurrent = classesArr[i];
			var cNext = classesArr[i+1];
			//var cPrev = 0;

			var currentStartHour =  parseInt(cCurrent.startHour);
			var currentEndHour = parseInt(cCurrent.endHour);
			var nextStartHour = parseInt(cNext.startHour);

			if (cCurrent.day == cNext.day && currentEndHour > nextStartHour) {
				//update previous
				for (var j = i - currentDepth; j <= i; j++) {
					depths[j] = currentDepth + 1;
				}

				currentDepth++;
				depths[i + 1] = currentDepth;
			}
			else {
				var isCollideWithPrev = false;
				for(var k=0; k < i ; k++){
					var cPrev = classesArr[k];
					var prevEndHour = parseInt(cPrev.endHour);
					if(cPrev.day == cNext.day && prevEndHour > nextStartHour){
						depths[i+1] = depths[k] * -2;
						isCollideWithPrev = true;
					}
				}

				if(!isCollideWithPrev){
					currentDepth = 0;
					depths[i + 1] = 0;
				}
			}
		}

		return(depths);
	}

	function sortClassesByTime(){
		var currSemester = window.bidit_globals.g_currSemester;
		var oldClasses = window.bidit_globals.g_schedulesArr[currSemester];
		var classes = new Array();

		//order all classes by time
		for (var i = 0; i < oldClasses.length; i++) {
			var c = oldClasses[i];
			var cDay = getDayNum(c.day) + 1;
			var cEndHour = parseInt(getHour(c.endHour).replace(/^0+/, ''));
			var cStartHour = parseInt(getHour(c.startHour).replace(/^0+/, ''));

			var added = false;

			for (var k = 0; k < classes.length; k++) {

				var kDay = getDayNum(classes[k].day) + 1;
				var kEndHour = parseInt(getHour(classes[k].startHour).replace(/^0+/, ''));
				var kStartHour = parseInt(getHour(classes[k].startHour).replace(/^0+/, ''));
				var cVal = cStartHour + cDay * 10000;
				var kVal = kStartHour + kDay * 10000;

				if (kVal > cVal) {
					if (k > 0) {
						classes.splice(k, 0, c);
					}
					else {
						classes.splice(0, 0, c);
					}
					added = true;
					break;
				}
				else if (kVal == cVal) {

					if (k + 1 < classes.length) {
						classes.splice(k + 1, 0, c);
						added = true;
						break;
					}
					else {
						classes.push(c);
						added = true;
						break;
					}
				}
			}
			if (!added) {

				classes.push(c);
			}
		}
		return classes;
	}


	//returns an array of course numbers from g_newChosenCourseArr
	function getCourseNumbersFromNewChosecourses(){
		var res=[];
		for (var i=0;i<window.bidit_globals.g_newChosenCoursesArr.length;i++){
			res[i]=window.bidit_globals.g_newChosenCoursesArr[i][0];
		}
		return res;


	}
	//returns the index of the tupple by course number. will return -1 if course number doesn't exist in g_newchosencoursearr
	function getIndexForNewChosenCoursesArr(courseNumber){
		var res = -1;
		for (var i=0;i<window.bidit_globals.g_newChosenCoursesArr.length;i++){
			if (window.bidit_globals.g_newChosenCoursesArr[i][0]==courseNumber){
				res = i;
			}
		}

		return res;
	}

	$(window).resize(function() {
		$("html").width($(window).width());
		clearTimetableView();
		updateTimeTableView();
	});


	$('#accordion2').delegate('#mInfoBtn','mouseenter',function(){
		$(this).addClass('icon-white');
		window.bidit_globals.g_currCourseProfile = $(this).closest('div').attr('id');
		window.bidit_globals.g_currChosenInfoBtnDepart = window.bidit_globals.g_currCourseProfile.substring(0,4);
		window.bidit_globals.g_isProfileOpenedFromMain = true;
		courseProfileInit();
		
		$(this).on('click', function(){
			$('#tab3x').empty();
			abortAllSyllabusRequests();
			syllabusRequestAjax = $.ajax({
				type: "GET",
				url: "/ajax/get-syllabus/",
				dataType: 'json', 
				data: { 'university': window.bidit_globals.g_currUniversity,
					'semester': (window.bidit_globals.g_currSemester+1),
					'course_num': window.bidit_globals.g_currCourseProfile },
					success: function(data)
					{
						syllabusRequestAjax = null;
						showCourseSyllabus(data);
					}
			});//ajax closed

			$.when(getCurrentCourseFromAjax()).done(function(a3, textStatus, jqXHR){
				unAssignCourseProfileData();
				checkIfCanAssignProfileData(a3);
				$('#courseProfileModal').modal('show');
			});	
		});
	});

	$('#accordion2').delegate('#mInfoBtn','mouseleave',function(){
		$(this).removeClass('icon-white');
	});

	$('#accordion2').delegate('#mChosenCourseRemove','mouseenter',function(){
		$(this).addClass('icon-white');
	});

	function findCourseIndexInAccordionsArr(currSemester,cNum){
		var accordArr = window.bidit_globals.g_allSemestersAccordions[currSemester];

		for(var i=0; i < accordArr.length; i++){
			if(accordArr[i].cNum == cNum){
				return i;
			}
		}

		return -1;
	}

	/**
	 * Use for removing course details from the relevant data structures:
	 * 1. g_coursesDisplaySettings
	 * 2. g_allSemestersAccordions
	 */
	function removeCourseFromDataStructuresHelper(currSemester, cNum){
		var cAccordIndex = findCourseIndexInAccordionsArr(currSemester, cNum);
		while(cAccordIndex != -1){
			window.bidit_globals.g_allSemestersAccordions[currSemester].splice(cAccordIndex,1);
			cAccordIndex = findCourseIndexInAccordionsArr(currSemester, cNum);
		}


		var courseIndex = window.bidit_globals.g_chosenCoursesArr[currSemester].indexOf(cNum);
		window.bidit_globals.g_chosenCoursesArr[currSemester].splice(courseIndex,1);


		//Deleting the course key from the display settings global array
		try{
			delete ((window.bidit_globals.g_coursesDisplaySettings[currSemester])[cNum]);

		}catch(e){}

	}

	function removeCourseFromMain(cNum,viaPend){
		var currSemester = window.bidit_globals.g_currSemester;
		var currCourseObj =  (window.bidit_globals.g_coursesDisplaySettings[currSemester])[cNum];


		$('#lc'+cNum).removeClass('course-cell-disabled');
		$('#lc'+cNum).addClass('depart-cell-hover');

		$('div[name="ag' + cNum +'"]').remove();

		$.each(currCourseObj.groups,function(){
			var currGroupObj = this;

			// Update total hours of courses in schedual
			if(currGroupObj.gChosen){
				UpdateTotalHours(currSemester,currGroupObj,'remove',false,true);
			}

			//Deleting course classes("mifgashim") from schedual arr
			removeGroupFromSchedule(cNum,currGroupObj.gNum);

		});


		if(currCourseObj.cChosen){
			UpdateZchutHours(currSemester,currCourseObj,'remove',true);
		}

		var courseColor = (window.bidit_globals.g_coursesDisplaySettings[currSemester])[cNum].cColor; 
		if(courseColor != 'white'){
			var colorIndex = window.bidit_globals.g_scheduleColors.indexOf(courseColor);
			if(colorIndex != -1){
				window.bidit_globals.g_scheduleColors.splice(colorIndex,1);
				window.bidit_globals.g_colorsStock.push(courseColor);
			}
		}		

		removeCourseFromDataStructuresHelper(currSemester, cNum);

		clearTimetableView();

		updateTimeTableView();
		
		/*refreshing the calendar and exams*/
		updateExamsAndCalendar();
		
		/*clear and foucs on course search*/
		//clearAndFocusCourseSearch();

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

		//Need to save data
		if(currSemester == 0){
			localStorage.isDataSaved_A = '0';
		}
		else{
			localStorage.isDataSaved_B = '0';
		}


		//Updating total hours and total zchut hours for current semester
		$('#totalHours').text('שעות: ' + window.bidit_globals.g_totalHoursArr[currSemester]);
		$('#totalZchutHours').text('נקודות זכות: ' + window.bidit_globals.g_totalZchutHoursArr[currSemester]);

		/*if there are courses show the optimizer button*/
		showOrHideOptimizeButton();


	}

	/* The user removed a course from main screen accordion */
	$('#accordion2').delegate('#mChosenCourseRemove','click',function(){
		var cNum = $(this).closest('div').attr('id');

		var currSemester = window.bidit_globals.g_currSemester;
		var otherSemester = getOtherSemester(currSemester);
		var cAccordIndex = findCourseIndexInAccordionsArr(currSemester, cNum);
		var courseInfoObj = window.bidit_globals.g_allSemestersAccordions[currSemester][cAccordIndex];

		var isCourseYearly = checkIfCourseIsYearly(courseInfoObj);
		if(isCourseYearly){

			var groupNums = getGroupNumsArr(courseInfoObj);
			deleteFromDataStructAnotherSem(cNum, groupNums, otherSemester);	
		}

		removeCourseFromMain(cNum,false);

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);


	});

	$('#accordion2').delegate('#mChosenCourseRemove','mouseleave',function(){
		$(this).removeClass('icon-white');
	});

	/* The user's mouse is over a course in the main accordion */
	$('#accordion2').delegate('.accordion-group','mouseenter',function(){
		var infoBtnElement = $(this).find('#mInfoBtn');
		var removeBtnElement = $(this).find('#mChosenCourseRemove');

		infoBtnElement.children().css('opacity','100');
		removeBtnElement.children().css('opacity','100');

	});

	$('#accordion2').delegate('.accordion-group','mouseleave',function(){
		var infoBtnElement = $(this).find('#mInfoBtn');
		var removeBtnElement = $(this).find('#mChosenCourseRemove');

		infoBtnElement.children().css('opacity','0.8');
		removeBtnElement.children().css('opacity','0.8');

	});

	/* The user clicked a class on the main screen shcedule */
	$('body').delegate('.ttClass','click',function(){
		var courseNum = $(this).attr('id');


		$('#accTog'+courseNum).click();
		
		/*arbel*/
		showCourseExamClickByCourseNum(courseNum);

	});

	
	function showOrHideOptimizeButton(){

		if (window.bidit_globals.g_chosenCoursesArr[window.bidit_globals.g_currSemester].length!=0){
			$('#coursesNotChosenYetText').text('');
			/*comment the next line to hide the OPTIMIZE BUTTON
			for all time*/
			$('#optimizeBtnGroup').removeClass('hide');
			
			$('#goToPrint').removeClass('hide');

		}
		else{
			$('#coursesNotChosenYetText').text('-לא נבחרו קורסים-');
			$('#coursesNotChosenYetText').css('margin','15px');
			$('#coursesNotChosenYetText').css('font-size','large');
			$('#coursesNotChosenYetText').css('text-align','center');
			/*comment the next line to hide the OPTIMIZE BUTTON
			for all time*/
			$('#optimizeBtnGroup').addClass('hide'); 
			
			$('#goToPrint').addClass('hide');

		}
	}


	/*external function to shuffle an array for the colors to be random*/
	function arrayShuffle(theArray) {
		var len = theArray.length;
		var i = len;
		while (i--) {
			var p = parseInt(Math.random()*len);
			var t = theArray[i];
			theArray[i] = theArray[p];
			theArray[p] = t;
		}
	};

	function openFirstAccordion(currAccordion){
		var currSem = window.bidit_globals.g_currSemester;
		var firstNum = currAccordion[0].cNum;	
		window.setTimeout(function () {
			$('#accTog'+firstNum).click();
		}, 1000);
	}

	/*================================================================================================
	 *                                       Contact
	 *================================================================================================	
	 */


	var validator = $('#contact-form').validate(
			{
				rules: {
					name: {
						minlength: 2,
						required: true
					},
					email: {
						//minlength: 2,
						required: true,
						email: true
					},
					subject: {
						minlength: 2,
						required: true
					},
					message: {
						minlength: 2,
						required: true
					}
				},
				highlight: function(element) {




					$(element).closest('.control-group').removeClass('success').addClass('error');

					var thing = $(element).closest('div').attr('id');
					var valSign = getCorrectValidSignArea(thing);
					$('#'+valSign).empty();
					window.bidit_globals.g_contactFormBool[thing]=false;

				},
				success: function(element) {
					var thing = element.closest('div').attr('id');
					var valSign = getCorrectValidSignArea(thing);

					window.bidit_globals.g_contactFormBool[thing]=true;

					$('#'+valSign).empty();
					$('#'+valSign).append('<img src="assets/img/valid.png" valign="top"/>');

					element
					.addClass('valid')
					.closest('.control-group').removeClass('error').addClass('success');
				}
			});




	function getCorrectValidSignArea(iden){


		switch (iden){
		case 'nameContact':    return 'nameContactValidSignArea';
		break;
		case 'emailContact':    return 'emailContactValidSignArea';
		break;
		case 'subjectContact':    return 'subjectValidSignArea';
		break;
		case 'freeText':    return 'freeTextValidSignArea';
		break;
		}

	}

	/*karin: sending mail on click. need to add to code above initialization to globals, after validating*/
	$('#submitSupportMail').click(function(){
		var contactBool = window.bidit_globals.g_contactFormBool;
		var isMSIE = false;
		if ((jQuery.browser.name.toLowerCase() == 'microsoft internet explorer') ||
				(navigator.userAgent.toLowerCase().indexOf('msie') > -1)){
			isMSIE = true;	
		}


		if (isMSIE == true){
			var sName = document.getElementById("name").value;
			var sMail = document.getElementById("email").value;
			var sSubject = document.getElementById("subject").value;
			var sBody = document.getElementById("message").value;



			if (sName == '') {
				window.bidit_globals.g_supportFromName = 'שם לא ידוע';
			}
			else {
				window.bidit_globals.g_supportFromName = sName;
			}
			if (sMail == '') {
				window.bidit_globals.g_supportFromMailTxt = 'מייל לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportFromMailTxt = sMail;
			}
			if (sSubject == '') {
				window.bidit_globals.g_supportMailSubject = 'נושא לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportMailSubject = sSubject;
			}
			if (sBody == '') {
				window.bidit_globals.g_supportMailBody = 'תוכן לא ידוע'; 
			}
			else {
				window.bidit_globals.g_supportMailBody = sBody;
			}
			sendSupportMail();
			$("body").animate({ scrollTop: 0}, 'fast'); 
		}
		else if ((contactBool['nameContact'] && 
				contactBool['emailContact'] &&
				contactBool['subjectContact'] &&
				contactBool['freeText']))
		{

			window.bidit_globals.g_supportFromName = document.getElementById("name").value;
			window.bidit_globals.g_supportFromMailTxt = document.getElementById("email").value;
			window.bidit_globals.g_supportMailSubject = document.getElementById("subject").value;
			window.bidit_globals.g_supportMailBody = document.getElementById("message").value;

			sendSupportMail();
			$("body").animate({ scrollTop: 0}, 'fast'); 

		}


		/*there are still missing areas*/
		else {
			showUnsentMessege();
			//validator;	
		}
	});

	function sendSupportMail(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/submitMail/",
			dataType: 'json',
			data: { 'toMail': window.bidit_globals.g_supportToMail,
				'fromMail': window.bidit_globals.g_supportFromMail,
				'fromMailTxt': window.bidit_globals.g_supportFromMailTxt,
				'fromName': window.bidit_globals.g_supportFromName,
				'body': window.bidit_globals.g_supportMailBody,
				'subject': window.bidit_globals.g_supportMailSubject},

				success: function(data){
					window.bidit_globals.g_supportFromName = '';
					window.bidit_globals.g_supportFromMailTxt = '';
					window.bidit_globals.g_supportMailSubject = '';
					window.bidit_globals.g_supportMailBody = '';
					resetContact();
					showSentMessege();

				}
		});//ajax closed
	}

	$('#resetContactFormButton').click(function(){
		resetContact();
	});


	function resetContact(){
		var contactBool = window.bidit_globals.g_contactFormBool;

		contactBool['nameContact'] = false; 
		contactBool['emailContact'] = false;
		contactBool['subjectContact'] = false;
		contactBool['freeText'] = false;

		$('#nameContactValidSignArea').empty();
		$('#emailContactValidSignArea').empty();
		$('#subjectValidSignArea').empty();
		$('#freeTextValidSignArea').empty();

		$('#name').val('');
		$('#email').val('');
		$('#subject').val('');
		$('#message').val('');


		$('#nameContact').removeClass('valid error success');
		$('#emailContact').removeClass('valid error success');
		$('#subjectContact').removeClass('valid error success');
		$('#freeTextContact').removeClass('valid error success');

		$('.control-group').removeClass('valid error success');

		hideSentOrUnsentMessege();	
		validator.resetForm();

		$('#contactExit2').removeClass('hide');
		$('#submitSupportMail').removeClass('hide');
		$('#backToMainScreenFromContact').addClass('hide');

	}

	function hideSentOrUnsentMessege(){
		$('#messegeSentArea').empty();
	}
	function showSentMessege(){
		$('#messegeSentArea').empty();
		var mPriority = 'warning';
		var messageToShow = 'נשלח בהצלחה';
		showAlert(messageToShow,mPriority);


		$('#contactModal').modal('hide');	
		$('#contactExit2').addClass('hide');
		/*$('#submitSupportMail').addClass('hide');*/
		$('#backToMainScreenFromContact').removeClass('hide');


	}

	$('#backToMainScreenFromContact').click(function(){
		resetContact();
		$('#contactModal').modal('hide');	

	});

	function showUnsentMessege(){


		$('#messegeSentArea').empty();
		$('#messegeSentArea').append(
				'<h5 style="color: red;"><strong>.אנא מלא את כל הפרטים</strong></h5>'
		);

	}

	$('#contactModal').on('hidden', function (){
		resetContact();

	});


	function showAlert() {
		$("#myAlert").removeClass("in");
	}



	function showAlert(messageToShow,messagePriority){

		$(document).trigger("add-alerts", [
		                                   {
		                                	   'message': '<div style="color:black;"><strong>'+ messageToShow +'</strong></div>',
		                                	   'priority': messagePriority
		                                   }
		                                   ]);


	}


	$('#contactViaAbout').click(function(){

		$('#aboutModal').modal('hide');	
		$('#contactBtnMain').click();
	});

	/*================================================================================================
	 *                                       Calendar
	 *================================================================================================
	 */


	$('#txtDate').datepicker({isRTL: true,numberOfMonths: 2 ,yearRange: "-50:+50",  
		monthNames: ['ינואר','פברואר','מרץ','אפריל','מאי','יוני',
		             'יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'],
		             monthNamesShort: ['1','2','3','4','5','6',
		                               '7','8','9','10','11','12'],
		                               dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
		                               dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
		                               dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
		                               dateFormat: 'dd/mm/yyyy',
		                               firstDay: 0,
		                               prevText: 'הקודם',  nextText: 'הבא' ,
		                               defaultDate: window.bidit_globals.g_firstExamDate,
		                               /*for some reason this doesnt work*/
		                               //dateFormat: 'dd/mm/yyyy',

		                               /*happens in every refresh of calendar like month change or reload*/
		                               beforeShowDay: highlightExams


	});



	function highlightExams(date) {
		/*these 3 arrays are coardinated with each other by indexes*/

		var dates = []; //array of dates
		var types = []; // array of arrays of types
		var moeds = []; // array of arrays of moeds
		var colors = []; // array of arrays of colors
		var names = []; // array of arrays of names
		var crashes = []; //array of binary identifier
		$('#ExclamationDiv').empty();
		return [true, colorExam(date,types,dates,moeds,colors,names,crashes),labelExams(date,types,dates,moeds,colors,names,crashes)];
		if (crashes.indexOf(true) == -1) {
			$('#ExclamationDiv').addClass('hide');
		}
	}



	function addMetaExamsToArrays(types,dates,moeds,colors,names,crashes){
		var i=0;
		for (i=0 ; i < window.bidit_globals.g_metaDatesDS["metaDates"].length ; i++){
			dates.push(window.bidit_globals.g_metaDatesDS["metaDates"][i]);
			types.push(window.bidit_globals.g_metaDatesDS["metaTypes"][i]);
			moeds.push(window.bidit_globals.g_metaDatesDS["metaMoeds"][i]);
			colors.push(window.bidit_globals.g_metaDatesDS["metaColors"][i]);
			names.push(window.bidit_globals.g_metaDatesDS["metaNames"][i]);
			crashes.push(window.bidit_globals.g_metaDatesDS["metaCrashes"][i]);
		}

	}

	function colorExam(date,types,dates,moeds,colors,names,crashes){

		/*semester A*/
		runOverSemester(0,date,types,dates,moeds,colors,names,crashes);
		/*semester B*/
		runOverSemester(1,date,types,dates,moeds,colors,names,crashes);

		/*adding the meta exams*/
		addMetaExamsToArrays(types,dates,moeds,colors,names,crashes);

		/*looping over the current chosen courses and colors the correct date*/
		for (var i = 0; i < dates.length; i++){
			var tmpDate = dates[i];
			var tmpMoed = moeds[i]; //array
			var tmpCol = colors[i]; //array
			var tmpCrash = crashes[i];
			if (tmpCrash==true){
				showExclamationMark();	
			}

			if (date.getTime() == (new Date(tmpDate).getTime())) {
				if (tmpCrash==true){
					/*in case like this need to monitor the user*/

					return 'colorDate'+'Overlap';
				}
				else if (tmpCrash==false){
					if (tmpCol[0] == 'Meta'){
						return 'colorDateMeta';
					}
					return 'colorDate'+tmpCol[0].substring(1,tmpCol[0].length);
				}
			}

		};



	}


	function runOverSemester(semester,date,types,dates,moeds,colors,names,crashes){
		$.each(window.bidit_globals.g_coursesDisplaySettings[semester],(function(){
			/*getting date*/
			/*in case the course is chosen*/
			if (this.cChosen == true){

				for (var i=0 ; i<this.dates.length ; i++){

					var day = getMonthFromString(this.dates[i]);
					var dateString ;
					var d = getDayFromString(this.dates[i]);
					var m = getMonthFromString(this.dates[i]);
					var y = getYearFromString(this.dates[i]);
					if (m.length==1) m="0"+m;
					dateString = m+"/"+d+"/"+y;
					/*case of date already exist, and legal date*/
					if ((dates.indexOf(dateString)) > -1 && (dateString != "//---")){
						/*in case duplicate due to yearly course*/
						if (checkIfYearly(this.cNum)){
							continue;
						}


						//no need to enter date
						var dateStringIndex = dates.indexOf(dateString);
						var pushedType = types[dateStringIndex];
						var pushedMoed = moeds[dateStringIndex];
						var pushedColor = colors[dateStringIndex];
						var pushedName = names[dateStringIndex];

						/*getting type*/
						pushedType[pushedType.length] = this.types[i];
						types[dateStringIndex]/*[0]*/ = pushedType;
						/*getting moed*/
						pushedMoed[pushedMoed.length] = this.moeds[i];
						moeds[dateStringIndex]/*[0]*/ = pushedMoed;
						/*getting color*/
						pushedColor[pushedColor.length] = this.cColor;
						colors[dateStringIndex]/*[0]*/ = pushedColor;
						/*getting name of the course*/
						pushedName[pushedName.length] = this.cName;
						names[dateStringIndex]/*[0]*/ = pushedName;
						/*crash*/
						crashes[dateStringIndex]=true;

						continue;

					}

					/*case of new date, and legal date*/
					if (dates.indexOf(dateString)== -1 && (dateString != "//---")) {
						//var pushedDate = [];
						var pushedType = [];
						var pushedMoed = [];
						var pushedColor = [];
						var pushedName = [];

						dates.push(dateString);
						/*getting type*/
						types.push([this.types[i]]);
						/*getting moed*/
						moeds.push([this.moeds[i]]);
						/*getting color*/
						colors.push([this.cColor]);
						/*getting name of the course*/
						names.push([this.cName]);
						/*no crash*/
						crashes.push(false);
						continue;

					}

				};
				
			};

		}));
	}



	function assignOldArray(realTypes,realMoed,realColor,realName,types,moeds,colors,names,index){

		var len = names[index].length;
		for (var i=0 ; i<len ; i++){
			types[index][i] = realTypes;
			moeds[index][i] = realMoed;
			colors[index][i] = realColor;
			names[index][i] =  realName;

		}

	}

	function labelExams(date,types,dates,moeds,colors,names,crashes){
		/*looping over the current chosen courses and label the correct text*/
		for (var i = 0; i < dates.length; i++){
			var tmpDate = dates[i]; //date
			var tmpMoedArr = moeds[i]; //array of moeds
			var tmpColArr = colors[i]; //array of colors
			var tmpNameArr = names[i]; //array of names
			var tmpTypeArr = types[i]; //array of types
			var tmpCrash = crashes[i]; //crash
			if (date.getTime() == (new Date(tmpDate).getTime()))  
				return printLabels(tmpDate,tmpColArr,tmpNameArr,tmpTypeArr,tmpMoedArr,tmpCrash);
		}	

	};


	function printLabels(tmpDate,tmpColArr,tmpNameArr,tmpTypeArr,tmpMoedArr,tmpCrash){



		if (tmpCrash == false){
			if (tmpTypeArr[0] == 'Meta'){
				return tmpNameArr[0];
			}
			return tmpNameArr[0]+": "+tmpTypeArr[0]+", מועד "+tmpMoedArr[0]+"'";
		}
		if (tmpCrash == true){
			var retString = '***חפיפה***\n';

			for (var j=0; j<tmpTypeArr.length; j++){
				retString +=
					tmpNameArr[j]+": "+tmpTypeArr[j]+", מועד "+tmpMoedArr[0]+"'"+'\n';

			}

			return retString;
		}
	}



	function showExclamationMark(){
		$('#ExclamationDiv').empty();
		$('#ExclamationDiv').append('<h4 style="color:red;" >*** קיימת חפיפה בין מועדי מבחנים ***</h4>');
	}



	function getDayFromString(str){
		var index=0;
		for(var i=0;i<str.length;i++){
			if (str[i]=='/')	{
				index=i;
				break;
			}
		}
		return str.substring(0,index);
	}

	function getMonthFromString(str){
		var index1=0;
		var index2=0;
		var thisTime = false;
		for(var i=0;i<str.length;i++){
			if (str[i]=='/'){
				index1=i+1;
				thisTime=true;
				continue;	
			}

			if (str[i]=='/' && thisTime)	{
				index2=i;
				break;
			}
		}
		return str.substring(str.indexOf('/')+1,str.indexOf('/',str.indexOf('/')+1));
	}

	function getYearFromString(str){
		var index1=0;
		var index2=0;
		var thisTime = false;
		for (var i=0;i<str.length;i++){
			if (str[i]=='/'){
				index1=i+1;
				thisTime=true;
				continue;	
			}
			if (str[i]=='/' && thisTime)	{
				index2=i;
				break;
			}
		}
		return str.substring(str.indexOf('/',str.indexOf('/')+1)+1,str.length);
	}

	/*should be called every time there is supposed to be change on examse, ncluding when the page loads*/

	function updateExamsAndCalendar(){

		$('#examsListBody').empty();

		$('#examsListBody').append(function(){
			var retString = "";
			var examsArraySorted = [];
			/*array which is the first element is dates, second is course name and the third is the color*/
			window.bidit_globals.g_examObj = [];
			var obj = window.bidit_globals.g_examObj;

			if (window.bidit_globals.g_printOnlyCurrSem == true){
				takeParamsToExamsListBody(window.bidit_globals.g_currSemester,obj);
			}
			else {
				/*semester A*/
				takeParamsToExamsListBody(0,obj);

				/*semester B*/
				takeParamsToExamsListBody(1,obj);	
			}


			/*sort the dates list and assign each color and name*/



			obj.sort(function(a, b) {
				var aDate = a[0];
				var bDate = b[0];
				return (aDate == bDate) ? 0 : ((aDate > bDate) ? 1 : -1);
			});

			/*in case of empty exams list the current date is today*/
			if (obj.length==0) {
				window.bidit_globals.g_firstExamDate = 'today';

			}
			/*else the current date the first exam date*/
			else {
				window.bidit_globals.g_firstExamDate = obj[0][0];
			}

			$('#txtDate').datepicker("setDate", window.bidit_globals.g_firstExamDate);

			for (var i=0 ; i<obj.length ; i++){
				var moedString = '';

				if (obj[i][5] == "בחינה סופית") {
					moedString = obj[i][1] + ', מועד ' + obj[i][4] + "'";
				}
				else {
					moedString =  obj[i][1] + ', מועד ' + obj[i][4] + "'"+
					' ('+ obj[i][5] + ')';
				}

				/*in case there is crash, the next line should be red*/
				if (crashDate(  printDate(obj[i][0]) ,  obj , obj[i][3])) {
					retString += '<tr style="direction:rtl; cursor: pointer; color: red; font-weight: bold;" id="'+obj[i][0]+'">'+
					'<td>' + 
					moedString +
					'</td>'+
					'<td>' +
					printDate(obj[i][0]) +
					'</td>' +
					'<td>'+
					'<font class="bulletSym" size="10" color="'+obj[i][2]+'">&#9679</font>'+
					'</td>'+
					'</tr>';
				}

				else {
					retString += '<tr style="direction:rtl; cursor: pointer;"'
						+' id="'+obj[i][0]+'"><td>' + 

						moedString +
						'</td>'+
						'<td>' +
						printDate(obj[i][0]) +
						'</td>' +
						'<td>'+
						'<font class="bulletSym" size="10" color="'+obj[i][2]+'">&#9679</font>'+
						'</td>'+
						'</tr>';
				}


			}

			//for each exam in increasing order


			if (retString == "") {
				retString += '<tr><td colspan="2">'+'-לוח המבחנים ריק-'+'</td></tr>';
			}{
				$('#txtDate').datepicker("refresh" );
				return retString;	
			}
		});	

		$('#txtDate').datepicker("refresh" );

	}

	/*only for showing bold text*/
	function crashDate(strDate,obj,strCourse){
		var times = 0;
		for (var i=0 ; i<obj.length ; i++){
			if (printDate(obj[i][0]) == (strDate) ) {
				times++;
			}
		}
		if (times > 1) return true;
		return false;

	}


	function takeParamsToExamsListBody(semester,obj){
		$.each(window.bidit_globals.g_coursesDisplaySettings[semester],(function()
				{
			
			/*in case the course is chosen*/
			if (this.cChosen == true){

				for (var i=0 ; i<this.dates.length ; i++){
					var day = getMonthFromString(this.dates[i]);
					var dateString ;
					var d = getDayFromString(this.dates[i]);
					var m = getMonthFromString(this.dates[i]);
					var y = getYearFromString(this.dates[i]);
					if (m.length==1) m="0"+m;
					dateString = m+"/"+d+"/"+y;
					var tmpObj = [];

					if (new Date(dateString)=="Invalid Date") continue;

					/*in case duplicate due to yearly course*/
					if (checkIfYearly(this.cNum)){
						if (alreadyInExamsList(this.cNum,this.moeds[i],this.types[i],obj)){
							continue;
						}
					}

					/*getting date*/
					tmpObj[0]=(new Date(dateString));

					/*getting name of the course*/
					tmpObj[1]=(this.cName);

					/*getting color*/
					tmpObj[2]=(this.cColor);

					/*getting number*/
					tmpObj[3]=(this.cNum);

					/*getting moed*/
					tmpObj[4]=(this.moeds[i]);

					/*getting type*/
					tmpObj[5]=(this.types[i]);

					/*getting semester*/
					tmpObj[6]=(semester);

					/*getting exam begin hour*/
					tmpObj[7]=(this['startMoedHours'][i]);

					/*getting exam end hour*/
					tmpObj[8]=(this['endMoedHours'][i]);

					obj.push(tmpObj);

				};
			}
				}));	
	}


	function printDate(date){
		var d = date.getDate();
		var m = date.getMonth()+1;
		var y = date.getFullYear();

		return d+"/"+m+"/"+(y+'').substring(2, 4);

	}

	function makeDateFromString(str){

		var d = str.substring(0,2);
		var m = str.substring(3,5);
		var y= str.substring(6,10);
		var dateFormat = m+"/"+d+"/"+y;
		return new Date(dateFormat);

	}

	function showCourseExamClickByCourseNum(courseNum){

		var curSem = window.bidit_globals.g_currSemester;
		$.each(window.bidit_globals.g_coursesDisplaySettings[curSem],(function(){

			if (this.cNum == courseNum) {

				if ((this.dates[0] != '---')&&(this.dates[0] != undefined)) {
					var dateToShowFirst = makeDateFromString(this.dates[0]);
					$('#txtDate').datepicker("setDate", dateToShowFirst);
				}
			}
		}));

		$('#txtDate').datepicker("refresh" );	
	}



	function showCourseExamClickByDate(date){
		var newDate = new Date(date);
		$('#txtDate').datepicker("setDate", newDate);
		$('#txtDate').datepicker("refresh" );
	}

	$('#examsListBody').delegate('tr','click',function() {
		showCourseExamClickByDate(this.id);
	});



	function checkIfYearly(courseNum){
		var retValue1 = false;
		var retValue2 = false;
		var index1 = -1;
		var index2 = -1;
		/*1st semester*/
		for (var i =0 ; i<window.bidit_globals.g_allSemestersAccordions[0].length ; i++){

			if (window.bidit_globals.g_allSemestersAccordions[0][i].cNum == courseNum) index1 = i;

		}

		if (index1> -1) retValue1 = window.bidit_globals.g_allSemestersAccordions[0][index1].isYearly;

		if (retValue1 == true || retValue1 == undefined) return true;

		/*2nd semester*/

		for (var i =0 ; i<window.bidit_globals.g_allSemestersAccordions[1].length ; i++){

			if (window.bidit_globals.g_allSemestersAccordions[1][i].cNum == courseNum) index2 = i;

		}

		if (index2> -1) retValue2 = window.bidit_globals.g_allSemestersAccordions[1][index2].isYearly;



		if (retValue2 == true || retValue2 == undefined) return true;

		return false;

	}


	function alreadyInExamsList(courseNum,courseMoed,courseType,obj){
		for (var i=0 ; i<obj.length ; i++){
			if (obj[i][3] == courseNum && obj[i][4] == courseMoed 
					&& obj[i][5] == courseType)
				return true;
		}
		return false;
	}
	/*================================================================================================
	 *                                        User Log-In
	 *================================================================================================
	 */

	function getLoginUrl(){
		requestAjax = $.ajax({
			type: "GET",
			url: "/login/",
			dataType: 'json',
			data: { },
			success: function(data){
				//The user is currently not logged in
				if(data.userLoginStr.urlKind == 'login')
				{
					$('#SignInOrOutText').text(' התחבר ');
					$('#userName').text('');
					$('#saveSchedule').hide();
					$('#loadSchedule').hide();
					//sync with google calendar buttons
					$('#googleCalendarSyncSchedule').hide();
					$('#googleCalendarSyncExams').hide();
					/*due to the extra buttons needed*/
					clearTimetableView();
					updateTimeTableView();

					/*showing or not the welcome page*/
					welcomeWebStorage();	

				}
				else{
					$('#SignInOrOutText').text(' התנתק ');
					$('#userName').text(data.userLoginStr.nickname); 
					$('#saveSchedule').show();
					$('#loadSchedule').show();

					//Sync with google calendar buttons
					$('#googleCalendarSyncSchedule').show();
					//$('#googleCalendarSyncExams').show();
					/*due to the extra buttons needed*/
					clearTimetableView();
					updateTimeTableView();	

					window.bidit_globals.g_userID = data.userLoginStr.userId;
					window.bidit_globals.g_userEmail = data.userLoginStr.email;
					window.bidit_globals.g_userNickName = data.userLoginStr.nickname;

					//check if before loging the user was in the facebook tab
					var toOpenCourseProfileFacebook = localStorage.courseProfileFacebook;
					if(toOpenCourseProfileFacebook == null){

						/*showing or not the welcome page*/
						welcomeWebStorage();	

					}
					else{
						if(toOpenCourseProfileFacebook == ''){

							/*showing or not the welcome page*/
							welcomeWebStorage();	

						}
						else{
							window.bidit_globals.g_currCourseProfile = toOpenCourseProfileFacebook;
							window.bidit_globals.g_currChosenInfoBtnDepart = window.bidit_globals.g_currCourseProfile.substring(0,4);
							window.bidit_globals.g_isProfileOpenedFromMain = true;
							courseProfileInit();
							localStorage.courseProfileFacebook = '';

							$('#tab3x').empty();
							abortAllSyllabusRequests();
							syllabusRequestAjax = $.ajax({
								type: "GET",
								url: "/ajax/get-syllabus/",
								dataType: 'json', 
								data: { 'university': window.bidit_globals.g_currUniversity,
									'semester': (window.bidit_globals.g_currSemester+1),
									'course_num': window.bidit_globals.g_currCourseProfile },
									success: function(data)
									{
										syllabusRequestAjax = null;
										showCourseSyllabus(data);
									}
							});//ajax closed

							$.when(getCurrentCourseFromAjax()).done(function(a3, textStatus, jqXHR){
								unAssignCourseProfileData();
								checkIfCanAssignProfileData(a3);
								$('#courseProfileModal').modal('show');

								//Initializing the facebook tab
								$('#courseProfileTabs a:eq(5)').tab('show');
								$('#coursProfileTabsContent div:eq(5)').tab('show');
								var hasClassDis = $('#popularityTab').hasClass('facebookTabBtnDisabled');
								if(hasClassDis == false){
									$('#popularityTab').addClass('facebookTabBtnDisabled');
									updatePopularityTab(true);
								}

							});	

						}
					}
				}
				window.bidit_globals.g_loginUrl = data.userLoginStr.currUrl;
				$('#signInButtonMainScreen').attr('name',data.userLoginStr.urlKind);

				requestAjax = $.ajax({
					type: "GET",
					url: "/",
					data: { },
					success: function(data){
						var linkAttr = $('#SyncAllExams').attr('name');

						if(linkAttr == 'yes'){
							window.bidit_globals.g_acsess = true;
							//$('#SyncAllExams > a').attr('href','');
							//$('#SyncSemesterAExams > a').attr('href','');
							//$('#SyncSemesterBExams > a').attr('href','');
							//alert($('#SyncSemesterBExams > a').attr('href'));
							//alert($('#SyncSemesterAExams > a').attr('href'));
							//alert($('#SyncAllExams > a').attr('href'));
							window.bidit_globals.g_url_to_access = '';
							//alert("data=success token -> g_acsess = true, g_url_to_access = ''");
						}
						else{
							window.bidit_globals.g_acsess = false;
							window.bidit_globals.g_url_to_access = data;
							//alert("data<>success token -> g_acsess = false, g_url_to_access = url to go to");
						}

						//if the user asked for sync, we need to see if he gave approval
						if(localStorage.syncExams){
							//alert("localStorage.syncExams = true");
							//if the user gave access - sync
							if(window.bidit_globals.g_acsess){
								//alert("g_acsess=true");
								deleteOldExamsAndSyncNew();
								//actuallSyncOfEachExam();
							}
							//if the user didn't give us his approval -
							//tell the user he didn't give us his approval, so no sync accured.
							else{
								//alert("g_acsess=false");
								//showAlert('לא אישרת גישה ל google calendar שלך, ולכן לא התבצע איתו סינכרון.','warning');
							}
						}
					}
				});//ajax closed	
			}
		});//ajax closed


	}

	function operateLogging(){
		getLoginUrl();
		localStorage.inWebsiteForTheFirstTime = "1";

		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);

		window.location.replace(window.bidit_globals.g_loginUrl);


	}

	$('#signInButtonMainScreen').click(function(){
		if($('#signInButtonMainScreen').attr('name') == 'logout'){

			if(typeof(Storage)!=="undefined"){

				// show alert
				if (localStorage.showLogoutAlert != '0' && (localStorage.isDataSaved_A == '0' || localStorage.isDataSaved_B == '0')){
					$('#alertModal').attr('name','LOGOUT');
					$('#neverShowAgainQuestAlert').prop('checked', false);
					var message1 = 'האם ברצונך לשמור את המערכת לפני שאתה מתנתק?';
					var message2 = 'שים לב: השמירה תתבצע עבור כל הסמסטרים';
					var header1 = 'התנתקות';
					$('#noAlert').show();
					$('#yesAlert').show();
					$('#cancelAlert').show();
					$('#approveAlert').hide();
					$('#alertContent').text(message1);
					$('#alertQuestion').text(message2);
					$('#alertHeader').text(header1);
					$('#alertModal').modal('show');
				}

				// dont show alert
				else{					
					FB.api("me/permissions","delete", function(response){/*do something if you want*/});
					window.bidit_globals.g_facebookUserID = '';
					operateLogging();
				}
			}
			else{
				$('neverShowAgainQuestAlertDiv').empty();
			}
		}

		else{
			window.location.replace(window.bidit_globals.g_loginUrl);
		}
	});



	function showStoredScheduleData(){
		var displaySettingsCookie = JSON.parse(localStorage.biditDisplaySettingsCookie);
		var scheduleInfoCookie = JSON.parse(localStorage.biditScheduleInfoCookie);
		var currSemesterStored = localStorage.currSemester;

		var cookieScheduleObj = {};
		cookieScheduleObj['coursesInfoArr'] = scheduleInfoCookie;
		cookieScheduleObj['displaySettingsArr'] = displaySettingsCookie;
		showLoadedSchedule(cookieScheduleObj,2);

		if (currSemesterStored == 1){

		}


	}


	/*================================================================================================
	 *                                       Save Schedule 
	 *================================================================================================
	 */


	$('#saveSemesterA').click(function(){
		saveSchedualForUser(0);
	});

	$('#saveSemesterB').click(function(){
		saveSchedualForUser(1);
	});

	$('#saveAllSemesters').click(function(){
		saveSchedualForUser(2);
	});

	function whichCoursesAreInSchedule(){
		var coursesArr = window.bidit_globals.g_coursesDisplaySettings;
		var chosenScheduleCourses = [];
		var chosenScheduleCoursesA = [];
		var chosenScheduleCoursesB = [];
		chosenScheduleCourses.push(chosenScheduleCoursesA);
		chosenScheduleCourses.push(chosenScheduleCoursesB);


		$.each(coursesArr[0],function(){
			var isCourseChosen = this.cChosen;
			var courseNum = this.cNum;
			if(isCourseChosen){
				chosenScheduleCourses[0].push(courseNum);
			}
		});

		$.each(coursesArr[1],function(){
			var isCourseChosen = this.cChosen;
			var courseNum = this.cNum;
			if(isCourseChosen){
				chosenScheduleCourses[1].push(courseNum);
			}
		});

		return chosenScheduleCourses;
	}

	function saveSchedualForUser(semesterToSave){
		//Update cookies that user saved his changes
		if(semesterToSave == 0){
			localStorage.isDataSaved_A = '1';
		}
		else if(semesterToSave == 1){
			localStorage.isDataSaved_B = '1';
		}
		else{
			localStorage.isDataSaved_A = '1';
			localStorage.isDataSaved_B = '1';
		}


		//Chosen courses in schedule
		var chosenCourses = whichCoursesAreInSchedule();

		ajaxSavedData = [];
		ajaxScheduleToSaveObj = {};

		ajaxScheduleToSaveObj['displaySettingsArr'] = window.bidit_globals.g_coursesDisplaySettings;
		ajaxScheduleToSaveObj['coursesInfoArr'] = window.bidit_globals.g_allSemestersAccordions;

		ajaxSavedData.push(window.bidit_globals.g_currUniversity);
		ajaxSavedData.push(window.bidit_globals.g_userID);
		ajaxSavedData.push(window.bidit_globals.g_userEmail);
		ajaxSavedData.push(window.bidit_globals.g_userNickName);
		ajaxSavedData.push(ajaxScheduleToSaveObj);
		ajaxSavedData.push(semesterToSave);
		ajaxSavedData.push(chosenCourses);

		requestAjax = $.ajax({
			type: "POST",
			url: "/ajax/saveUserData/",
			data: JSON.stringify(ajaxSavedData),
			success: function () {
				showAlert('המערכת שלך נשמרה בהצלחה','warning');
			}
		});
	}


	/*================================================================================================
	 *                                       Load Schedual 
	 *================================================================================================
	 */

	/**
	 * This function gets 2 arrays of courses numbers as parameters and returns
	 */
	function findCommonCourses(coursesArr1,coursesArr2){
		var commonCourses = [];

		for(var i=0; i < coursesArr1.length; i++){
			var courseNum = coursesArr1[i];
			var isCourseInBoth = coursesArr2.indexOf(courseNum);

			//if course isn't in both arrays
			if(isCourseInBoth == -1){
				// do nothing
			}
			else{
				commonCourses.push(courseNum);	
			}

		}

		return commonCourses;
	}

	function getSemesterYearlyCourses(semesterNum){
		var yearlyCoursesArr = [];
		var semesterCoursesInfoArr = window.bidit_globals.g_allSemestersAccordions[semesterNum];

		for ( var i = 0; i < semesterCoursesInfoArr.length; i++) {
			var cNum = semesterCoursesInfoArr[i].cNum;
			var isYearly = checkIfCourseIsYearly(semesterCoursesInfoArr[i]);
			if(isYearly){
				yearlyCoursesArr.push(cNum);
			}
		}

		return yearlyCoursesArr;
	}

	function semesterNotLoadedColorInit(semesterNum){
		var semesterCoursesDisplayArr = window.bidit_globals.g_coursesDisplaySettings[semesterNum];

		$.each(semesterCoursesDisplayArr, function(){
			var courseObj = this;
			var cNum = courseObj.cNum;
			var cColor = courseObj.cColor;
			if(courseObj.cChosen){
				var colorIndex = window.bidit_globals.g_colorsStock.indexOf(cColor);

				if(colorIndex != -1){
					window.bidit_globals.g_colorsStock.splice(colorIndex, 1);
					window.bidit_globals.g_scheduleColors.push(cColor);
				}
				// maybe we changed our colors
				else{
					var pickColor = window.bidit_globals.g_colorsStock.pop();
					(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[cNum].cColor = pickColor;
				}

			}
		});
	}

	$('#loadSemesterA').click(function(){
		loadScheduleForUser(0);
	});

	$('#loadSemesterB').click(function(){
		loadScheduleForUser(1);
	});

	$('#loadAllSemesters').click(function(){
		loadScheduleForUser(2);
	});

	function loadScheduleForUser(semesterToLoad){
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/loadUserData/",
			dataType: 'json',
			data: {'university': window.bidit_globals.g_currUniversity,
				'user_id': window.bidit_globals.g_userID,
				'user_email': window.bidit_globals.g_userEmail,
				'nick_name': window.bidit_globals.g_userNickName },
				success: function (data) {
					showLoadedSchedule(data,semesterToLoad);

					/*if there are courses show the optimizer button*/
					showOrHideOptimizeButton();

					showAlert('המערכת שלך נטענה בהצלחה','warning');
				}
		});
	}

	function showLoadedSchedule(schedualDataObj,semesterToLoad){
		var currSemester = window.bidit_globals.g_currSemester;
		var otherSemester = getOtherSemester(currSemester);

		clearTimetableView();

		//Initializing colors
		copyColorsArray();

		//Initializing global arrays
		window.bidit_globals.g_scheduleColors = [];	

		if(semesterToLoad != 2){
			var semesterNotLoaded = getOtherSemester(semesterToLoad);
			semesterNotLoadedColorInit(semesterNotLoaded);
		}

		//Update the chosen semester with the loaded data
		var yearlyCoursesA = [];
		var yearlyCoursesB = [];
		var commonCourses = [];
		if(semesterToLoad == 2){
			yearlyCoursesA = showLoadedSemester(schedualDataObj,0);
			yearlyCoursesB = showLoadedSemester(schedualDataObj,1);

			commonCourses = findCommonCourses(yearlyCoursesA,yearlyCoursesB);

			// Getting out of the arrays the common yearly courses
			for(var i=0; i < commonCourses.length; i++){
				var indexA = yearlyCoursesA.indexOf(commonCourses[i]);
				var indexB = yearlyCoursesB.indexOf(commonCourses[i]);
				yearlyCoursesA.splice(indexA,1);
				yearlyCoursesB.splice(indexB,1);
			}

			if(currSemester == 0){
				chosenCoursesAjaxRequest(yearlyCoursesB,true);

				addYearlyCoursesToOtherSemester(otherSemester, yearlyCoursesA);
			}
			else{
				chosenCoursesAjaxRequest(yearlyCoursesA,true);

				addYearlyCoursesToOtherSemester(otherSemester, yearlyCoursesB);
			}
		}
		else{
			var semesterNotLoaded = getOtherSemester(semesterToLoad);
			yearlyCoursesA = showLoadedSemester(schedualDataObj,semesterToLoad);
			var NotLoadedSemesterYearlyCoursesArr = getSemesterYearlyCourses(semesterNotLoaded);

			commonCourses = findCommonCourses(yearlyCoursesA,NotLoadedSemesterYearlyCoursesArr);

			// Getting out of the arrays the common yearly courses
			for(var i=0; i < commonCourses.length; i++){
				var indexA = yearlyCoursesA.indexOf(commonCourses[i]);
				var indexB = NotLoadedSemesterYearlyCoursesArr.indexOf(commonCourses[i]);
				yearlyCoursesA.splice(indexA,1);
				NotLoadedSemesterYearlyCoursesArr.splice(indexB,1);
			}

			if(currSemester == semesterToLoad){
				chosenCoursesAjaxRequest(NotLoadedSemesterYearlyCoursesArr,true);

				addYearlyCoursesToOtherSemester(otherSemester, yearlyCoursesA);
			}
			else{
				chosenCoursesAjaxRequest(yearlyCoursesA,true);

				addYearlyCoursesToOtherSemester(otherSemester, NotLoadedSemesterYearlyCoursesArr);
			}

		}

		//Update the current semester schedule and courses on screen
		showCurrentCoursesAndSchedule();

		//Update local storage with the latest data
		localStorage.biditDisplaySettingsCookie = JSON.stringify(window.bidit_globals.g_coursesDisplaySettings);
		localStorage.biditScheduleInfoCookie =  JSON.stringify(window.bidit_globals.g_allSemestersAccordions);
	}



	/**
	 * Loads the schedule of the given semester
	 * ----------------------------------------
	 **/
	function showLoadedSemester(schedualDataObj,semesterNum){
		window.bidit_globals.g_chosenCoursesArr[semesterNum] = [];
		window.bidit_globals.g_schedulesArr[semesterNum] = [];
		window.bidit_globals.g_coursesDisplaySettings[semesterNum] = {};
		var yearlyCourses = [];

		window.bidit_globals.g_allSemestersAccordions[semesterNum] = (schedualDataObj.coursesInfoArr)[semesterNum];

		//Updating schedule with saved data
		var semesterCoursesArr = window.bidit_globals.g_allSemestersAccordions[semesterNum];

		//Display settings loaded from DB
		var displaySettingsToLoad = (schedualDataObj.displaySettingsArr)[semesterNum];

		//Init total hours
		window.bidit_globals.g_totalHoursArr[semesterNum] = '0';
		window.bidit_globals.g_totalZchutHoursArr[semesterNum] = 0.0;

		if(semesterCoursesArr.length > 0){
			if(window.bidit_globals.g_currSemester == semesterNum){
				$('#coursesNotChosenYetText').text('');
			}

			//Strings for creating the courses objects
			var MAIN_STR = 'ראשית';
			var SUB_STR = 'משנית';
			var OPTION_STR = 'אפשרות';

			for(var i = 0; i < semesterCoursesArr.length; i++){
				var isCourseDisplayUndefined = false;
				var chosenGroupsCounter = 0;
				var cNum = semesterCoursesArr[i].cNum;
				window.bidit_globals.g_chosenCoursesArr[semesterNum].push(cNum);

				var isCourseYearly = checkIfCourseIsYearly(semesterCoursesArr[i]);
				if(isCourseYearly){
					yearlyCourses.push(cNum);
				}

				//General course information
				var groupsArr = semesterCoursesArr[i].kvutzaData;
				var courseHeading = semesterCoursesArr[i].cName + ' (' + semesterCoursesArr[i].cNum + ')';
				var numOfHavurot = semesterCoursesArr[i].havurotNum; 
				var courseName = semesterCoursesArr[i].cName;
				var courseZchutHours = semesterCoursesArr[i].zchutHours;

				// Tests Information
				var moed = semesterCoursesArr[i].kvutzaData[0].moed;
				var moedType = semesterCoursesArr[i].kvutzaData[0].moedType;
				var startMoedHours = semesterCoursesArr[i].kvutzaData[0].startMoedHours;
				var endMoedHours = semesterCoursesArr[i].kvutzaData[0].endMoedHours;
				var dates = semesterCoursesArr[i].kvutzaData[0].dates;
				var cChosen = false;
				var cColor = 'white';
				if(displaySettingsToLoad[cNum] == undefined){
					cChosen = false;
					cColor = 'white';
					isCourseDisplayUndefined = true;
				}
				else{
					cChosen = displaySettingsToLoad[cNum].cChosen;
					cColor = displaySettingsToLoad[cNum].cColor;
				}
				
				// (Display Settings) Initalizing and adding new course display object to global display array
				var courseObj = {};
				courseObj['cChosen'] = cChosen;
				courseObj['cNum'] = cNum;
				courseObj['cName'] = courseName;
				courseObj['chosenGroups'] = chosenGroupsCounter;
				courseObj['cColor'] = cColor;
				courseObj['cZchutHours'] = courseZchutHours;
				courseObj['groups'] = {};

				// Tests Information
				courseObj['types'] = moedType;
				courseObj['moeds'] = moed;
				courseObj['startMoedHours'] = startMoedHours;
				courseObj['endMoedHours'] = endMoedHours;
				courseObj['dates'] = dates;

				/* Iterates over the groups of one course */
				$.each(groupsArr,function(){
					var gKind = this.kind;
					var gHavura = getHavuraNum(this.havura);
					var gNum = this.gNum;
					var gLecturer = this.lecturer;
					var gOfenHoraa = this.ofenHoraa;
					var days = this.days;
					var startHours = this.beginHours;
					var endHours = this.endHours;
					var places = this.place;
					var gHours = formatTotalHours(this.amountHours);
					var gChosen = false;
					if(isCourseDisplayUndefined){
						gChosen = false;
					}
					else if(displaySettingsToLoad[cNum].groups[gNum.toString()] == undefined){
						gChosen = false;
					}
					else{
						gChosen = displaySettingsToLoad[cNum].groups[gNum.toString()].gChosen;
					}

					//Creating new group object
					var groupObj = {};
					groupObj['gNum'] = gNum;
					groupObj['gChosen'] = gChosen;
					groupObj['havura'] = gHavura;
					groupObj['startHours'] = startHours;
					groupObj['endHours'] = endHours;
					groupObj['daysArr'] = days;
					groupObj['places'] = places;
					groupObj['ofenHoraa'] = gOfenHoraa;
					groupObj['gHours'] = gHours;

					if(gKind == MAIN_STR){
						groupObj['kind'] = 'main';
					}
					else if(gKind == SUB_STR){
						groupObj['kind'] = 'sub';
					}

					//Adds the new group to the new course object
					courseObj.groups[gNum.toString()] = groupObj;
				});

				// Adds the new course object to the Display Settings array
				(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[cNum] = courseObj;

				// update colors array
				if(courseObj.cChosen){


					//Add zchut hours of this course to total hours
					UpdateZchutHours(semesterNum, courseObj,'add',true);

					var cColor = courseObj.cColor;
					var colorIndex = window.bidit_globals.g_colorsStock.indexOf(cColor);

					if(colorIndex != -1){
						window.bidit_globals.g_colorsStock.splice(colorIndex, 1);
						window.bidit_globals.g_scheduleColors.push(cColor);
					}
					// maybe we changed our colors
					else{
						var pickColor = window.bidit_globals.g_colorsStock.pop();
						(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[cNum].cColor = pickColor;
					}



					$.each(courseObj.groups,function(){
						if(this.gChosen){
							chosenGroupsCounter = chosenGroupsCounter + 1;

							//Show classes of this group on schedule
							addGroupToSchedule(semesterNum,cNum,this.gNum,this.startHours,this.endHours,this.daysArr,this.places);

							//add group hours to total hours 
							UpdateTotalHours(semesterNum,this, 'add',false,true);

						}
					});

					(window.bidit_globals.g_coursesDisplaySettings[semesterNum])[cNum].chosenGroups = chosenGroupsCounter;
				}
			}
		}

		return yearlyCourses;
	}


	/*================================================================================================
	 *                     				google calendar sync exams
	 *================================================================================================*/	

	$('#SyncSemesterAExams').click(function(){
		localStorage.semesterToSync = 0;
		localStorage.syncExams = true;
	});

	$('#SyncSemesterBExams').click(function(){
		localStorage.semesterToSync = 1;
		localStorage.syncExams = true;
	});

	$('#SyncAllExams').click(function(){
		localStorage.semesterToSync = 2;
		localStorage.syncExams = true;
	});



	//delete old exams and sync new ones by user choice
	function deleteOldExamsAndSyncNew(){
		showAlert('מסנכרן מבחנים...','warning');
		window.bidit_globals.g_examObj2 = window.bidit_globals.g_examObj;
		updateTo2();
		//get all old event links from DS
		requestAjax = $.ajax({
			type: "GET",
			url: "/ajax/getOldExamsLinks/",
			dataType: 'json',
			data: { 'currUniversity': window.bidit_globals.g_currUniversity,
				'userId': window.bidit_globals.g_userID},
				success: function(data){
					//an array of 3 arrays - old links of sem A, sem B and year
					var oldExamsLinks = data.response;
					//if chosen sem A => delete sem A and year courses, sync sem A and year courses, save new sem A links and year links to DB
					if(localStorage.semesterToSync == 0){
						syncSemAExams(oldExamsLinks);					
					}
					//else if chosen sem B => delete sem B and year courses, sync sem A and year courses, save new sem B links and year links to DB
					else{
						if(localStorage.semesterToSync == 1){
							syncSemBExams(oldExamsLinks);
						}
						//else if chosen allSem => delete both semesters courses and year courses, sync both semesters and year courses, save new links to DB
						else{
							syncAllSemExams(oldExamsLinks);
						}
					}
				}
		});
	}



	//delete add and save sem A and all year exams
	function syncSemAExams(oldExamsLinks){
		var oldExamsLinksSemA = oldExamsLinks[0].concat(oldExamsLinks[2]);
		//if there are old events to delete => delete old events, add new ones and save to DB
		if (oldExamsLinksSemA.length>0){
			var numOfEventsToDelete = oldExamsLinksSemA.length;
			var numOfEventsDeleted = 0;
			$.each(oldExamsLinksSemA , function(){
				var ToSend = [];
				var requestType = 'deleteEvent';
				ToSend.push(requestType);
				ToSend.push(this);
				requestAjax = $.ajax({
					type: "POST",
					url: "/",
					dataType: 'json', 
					data: JSON.stringify(ToSend),
					success: function (data) {
						numOfEventsDeleted = numOfEventsDeleted+1;
						//if deleted all old events => add new events and save to DB
						if(numOfEventsDeleted == numOfEventsToDelete){
							addSemAExams(oldExamsLinks[1]);
						}
					}
				});
			});
		}
		//if there are no old events to delete => add new ones and save to DB
		else{
			addSemAExams(oldExamsLinks[1]);
		}
	}



	//add and save sem A exams
	function addSemAExams(oldSemBExamsLinks){
		var eventLinksToSave = [[],oldSemBExamsLinks,[]];
		//if there are no new events to add => just save in DB
		if(countNumberOfCoursesNeededToBeAdded()==0){
			saveEventLinksToDB(eventLinksToSave);										
		}
		//if there are new events to add => add and save events in DB
		else{
			var numOfEventsAdded = 0;
			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
			//for every exam in list of exams to sync
			$.each(window.bidit_globals.g_examObj2 , function() { 
				if(this[6] == 0 || this[6] == 2){
					var courseSem = this[6];
					//create data structure to send to request
					var arrayToSend1 = [];
					var requestType = 'createEvent';
					arrayToSend1.push(requestType);
					this[0] = printDate(this[0]);
					arrayToSend1.push(this);
					requestAjax = $.ajax({
						type: "POST",
						url: "/",
						dataType: 'json', 
						data: JSON.stringify(arrayToSend1),
						success: function (data) {
							if(data.response == -1){
								showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
								var stateObj = { obj: "URL" };
								history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
								var badURL = $('#SyncAllExams > a').attr('href');
								var indexOfToken = badURL.toLowerCase().indexOf("token");
								if (indexOfToken >= 0){
									$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
									$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
									$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
								}
							}
							else{
								numOfEventsAdded = numOfEventsAdded+1;
								eventLinksToSave[courseSem].push(data.response);
								//if finished adding events => save to DB
								if(numOfEventsToAdd == numOfEventsAdded){
									saveEventLinksToDB(eventLinksToSave);								
								}
							}
						}
					});
				}
			});
		}
	}


	//delete add and save sem B and all year exams
	function syncSemBExams(oldExamsLinks){
		var oldExamsLinksSemB = oldExamsLinks[1].concat(oldExamsLinks[2]);
		//if there are old events to delete => delete old events, add new ones and save to DB
		if (oldExamsLinksSemB.length>0){
			var numOfEventsToDelete = oldExamsLinksSemB.length;
			var numOfEventsDeleted = 0;
			$.each(oldExamsLinksSemB , function(){
				var ToSend = [];
				var requestType = 'deleteEvent';
				ToSend.push(requestType);
				ToSend.push(this);
				requestAjax = $.ajax({
					type: "POST",
					url: "/",
					dataType: 'json', 
					data: JSON.stringify(ToSend),
					success: function (data) {
						numOfEventsDeleted = numOfEventsDeleted+1;
						//if deleted all old events => add new events and save to DB
						if(numOfEventsDeleted == numOfEventsToDelete){
							addSemBExams(oldExamsLinks[0]);
						}
					}
				});
			});
		}
		//if there are no old events to delete => add new ones and save to DB
		else{
			addSemBExams(oldExamsLinks[0]);
		}
	}



	//add and save sem B exams
	function addSemBExams(oldSemAExamsLinks){
		var eventLinksToSave = [oldSemAExamsLinks,[],[]];
		//if there are no new events to add => just save in DB
		if(countNumberOfCoursesNeededToBeAdded()==0){
			saveEventLinksToDB(eventLinksToSave);										
		}
		//if there are new events to add => add and save events in DB
		else{
			var numOfEventsAdded = 0;
			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
			//for every exam in list of exams to sync
			$.each(window.bidit_globals.g_examObj2 , function() { 
				if(this[6] == 1 || this[6] == 2){
					var courseSem = this[6];
					//create data structure to send to request
					var arrayToSend1 = [];
					var requestType = 'createEvent';
					arrayToSend1.push(requestType);
					this[0] = printDate(this[0]);
					arrayToSend1.push(this);
					requestAjax = $.ajax({
						type: "POST",
						url: "/",
						dataType: 'json', 
						data: JSON.stringify(arrayToSend1),
						success: function (data) {
							if(data.response == -1){
								showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
								var stateObj = { obj: "URL" };
								history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
								var badURL = $('#SyncAllExams > a').attr('href');
								var indexOfToken = badURL.toLowerCase().indexOf("token");
								if (indexOfToken >= 0){
									$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
									$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
									$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
								}
							}
							else{
								numOfEventsAdded = numOfEventsAdded+1;
								eventLinksToSave[courseSem].push(data.response);
								//if finished adding events => save to DB
								if(numOfEventsToAdd == numOfEventsAdded){
									saveEventLinksToDB(eventLinksToSave);								
								}
							}
						}
					});
				}
			});
		}
	}


	//delete add and save all sem exams
	function syncAllSemExams(oldExamsLinks){
		var oldExamsLinksAllSem = oldExamsLinks[0].concat(oldExamsLinks[1],oldExamsLinks[2]);
		//if there are old events to delete => delete old events, add new ones and save to DB
		if (oldExamsLinksAllSem.length>0){
			var numOfEventsToDelete = oldExamsLinksAllSem.length;
			var numOfEventsDeleted = 0;
			$.each(oldExamsLinksAllSem, function(){
				var ToSend = [];
				var requestType = 'deleteEvent';
				ToSend.push(requestType);
				ToSend.push(this);
				requestAjax = $.ajax({
					type: "POST",
					url: "/",
					dataType: 'json', 
					data: JSON.stringify(ToSend),
					success: function (data) {
						numOfEventsDeleted = numOfEventsDeleted+1;
						//if deleted all old events => add new events and save to DB
						if(numOfEventsDeleted == numOfEventsToDelete){
							addAllSemExams();
						}
					}
				});
			});
		}
		//if there are no old events to delete => add new ones and save to DB
		else{
			addAllSemExams();
		}
	}




	//add and save all sem exams
	function addAllSemExams(){
		var eventLinksToSave = [[],[],[]];
		//if there are no new events to add => just save in DB
		if(countNumberOfCoursesNeededToBeAdded()==0){
			saveEventLinksToDB(eventLinksToSave);										
		}
		//if there are new events to add => add and save events in DB
		else{
			var numOfEventsAdded = 0;
			var numOfEventsToAdd = countNumberOfCoursesNeededToBeAdded();
			//for every exam in list of exams to sync
			$.each(window.bidit_globals.g_examObj2 , function() { 
				var courseSem = this[6];
				//create data structure to send to request
				var arrayToSend1 = [];
				var requestType = 'createEvent';
				arrayToSend1.push(requestType);
				this[0] = printDate(this[0]);
				arrayToSend1.push(this);
				requestAjax = $.ajax({
					type: "POST",
					url: "/",
					dataType: 'json', 
					data: JSON.stringify(arrayToSend1),
					success: function (data) {
						if(data.response == -1){
							showAlert('סינכרון \"'+data.msg+'\" לא הצליח','warning');
							var stateObj = { obj: "URL" };
							history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
							var badURL = $('#SyncAllExams > a').attr('href');
							var indexOfToken = badURL.toLowerCase().indexOf("token");
							if (indexOfToken >= 0){
								$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
								$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
								$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
							}
						}
						else{
							numOfEventsAdded = numOfEventsAdded+1;
							eventLinksToSave[courseSem].push(data.response);
							//if finished adding events => save to DB
							if(numOfEventsToAdd == numOfEventsAdded){
								saveEventLinksToDB(eventLinksToSave);								
							}
						}
					}
				});
			});
		}
	}	


	//save event links list in DB
	function saveEventLinksToDB(eventLinksToSave){
		var arrayToSend = [];
		arrayToSend.push(window.bidit_globals.g_currUniversity);
		arrayToSend.push(window.bidit_globals.g_userID);
		arrayToSend.push(window.bidit_globals.g_userEmail);
		arrayToSend.push(window.bidit_globals.g_userNickName);
		arrayToSend.push(eventLinksToSave);
		requestAjax = $.ajax({
			type: "POST",
			url: "/ajax/saveEventLinksToDS/",
			dataType: 'json', 
			data: JSON.stringify(arrayToSend),
			success: function (data) {
				showAlert('המבחנים סונכרנו בהצלחה','warning');
				localStorage.syncExams = false;
				localStorage.semesterToSync = -1;
				var stateObj = { obj: "URL" };
				history.replaceState(stateObj, "page", "http://bid-it.appspot.com/");
				var badURL = $('#SyncAllExams > a').attr('href');
				var indexOfToken = badURL.toLowerCase().indexOf("token");
				if (indexOfToken >= 0){
					$('#SyncAllExams > a').attr('href',badURL.substring(0,indexOfToken));
					$('#SyncSemesterAExams > a').attr('href',badURL.substring(0,indexOfToken));
					$('#SyncSemesterBExams > a').attr('href',badURL.substring(0,indexOfToken));
				}
			}
		});
	}



	//counts number of exams needed to be added
	function countNumberOfCoursesNeededToBeAdded(){
		var n = 0;
		allExams = window.bidit_globals.g_examObj2;
		chosenSem = localStorage.semesterToSync;
		if(chosenSem==0){
			$.each(allExams , function(){
				if(this[6]==0 || this[6]==2){
					n = n+1;
				}			
			});
		}
		else{
			if(chosenSem==1){
				$.each(allExams , function(){
					if(this[6]==1 || this[6]==2){
						n = n+1;
					}			
				});
			}
			else{
				$.each(allExams , function(){
					n = n+1;		
				});
			}
		}
		return n;
	}




	/*this function update each semester of g_examObj2 (which is the copy) to be 2 if the course is yearly regardless if it is only in one semester on the time table*/
	function updateTo2(){
		$.each(window.bidit_globals.g_examObj2 , function() {
			if (checkIfYearly(this[3])){
				this[6] = 2;
			}
		});
	}




	/*================================================================================================
	 *                                    Read More
	 *================================================================================================*/	




	$("#readMoreModal").on('shown', function (){
		$('#chooseCoursesStep').click();
	});

	$('#chooseCoursesStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').addClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","block");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').addClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#catalogsStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').addClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","block");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').addClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');
	});

	$('#optimizeStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');     

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').addClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","block");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').addClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#extraStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');     

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').addClass('current');
		$('#changesStep').removeClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","block");
		$('#stepChanges').css("display","none");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').addClass('badge-inverse');
		$('#changesBadge').removeClass('badge-inverse');

	});	

	$('#changesStep').click(function(){
		$("#readMoreBody").animate({ scrollTop: 0}, 'fast');    

		$('#chooseCoursesStep').removeClass('current');
		$('#catalogsStep').removeClass('current');
		$('#optimizeStep').removeClass('current');
		$('#extraStep').removeClass('current');
		$('#changesStep').addClass('current');

		$('#stepChooseCourses').css("display","none");
		$('#stepCatalog').css("display","none");
		$('#stepOptimize').css("display","none");
		$('#stepExtra').css("display","none");
		$('#stepChanges').css("display","block");

		$('#chooseCoursesBadge').removeClass('badge-inverse');
		$('#catalogBadge').removeClass('badge-inverse');
		$('#optimizeBadge').removeClass('badge-inverse');
		$('#extraBadge').removeClass('badge-inverse');
		$('#changesBadge').addClass('badge-inverse');

	});


	$('#nextStep1').click(function(){
		$('#catalogsStep').click();
	});
	$('#prevStep1').click(function(){

	});
	$('#nextStep2').click(function(){
		$('#optimizeStep').click();

	});
	$('#prevStep2').click(function(){

		$('#chooseCoursesStep').click();
	});
	$('#nextStep3').click(function(){
		$('#changesStep').click();
	});
	$('#prevStep3').click(function(){
		$('#catalogsStep').click();
	});
	$('#nextStep4').click(function(){
		$('#extraStep').click();
	});
	$('#prevStep4').click(function(){
		$('#optimizeStep').click();
	});


	$('#nextStep5').click(function(){

	});
	$('#prevStep5').click(function(){
		$('#changesStep').click();
	});


	/*================================================================================================
	 *                                       ALERT MODAL HANDLE
	 *================================================================================================*/

	$('#neverShowAgainQuestAlert').change(function() {

		if ($("#neverShowAgainQuestAlert").is(':checked')) {

			var operationName =  $('#alertModal').attr('name');
			switch (operationName){
			case 'OPTIMIZE':    localStorage.showOptimizerAlert = '0';
			break;
			case 'LOGOUT': 		localStorage.showLogoutAlert = '0';
			break;
			}

		}
		else {

			var operationName =  $('#alertModal').attr('name');
			switch (operationName){
			case 'OPTIMIZE':    localStorage.showOptimizerAlert = '1';
			break;
			case 'LOGOUT': 		localStorage.showLogoutAlert = '1';
			break;
			}

		}

	});

	$('#cancelAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'OPTIMIZE':   
			break;		
		case 'LOGOUT':
			break;
		}
	});

	$('#approveAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'OPTIMIZE':    operateOptimizer();
		$('#optimizeModal').modal('hide');
		break;		
		}
	});

	$('#yesAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'LOGOUT':  saveSchedualForUser(2);
		FB.api("me/permissions","delete", function(response){/*do something if you want*/});
		window.bidit_globals.g_facebookUserID = '';
		operateLogging();
		break;
		}
	});

	$('#noAlert').click(function(){
		$('#alertModal').modal('hide');

		var operationName =  $('#alertModal').attr('name');
		switch (operationName){
		case 'LOGOUT': FB.api("me/permissions","delete", function(response){/*do something if you want*/});
		window.bidit_globals.g_facebookUserID = '';
		operateLogging();
		break;
		}
	});

	/*================================================================================================
	 *                                      html2canvas 
	 *================================================================================================
	 */

	$('.navbar').load(function(){
		clearTimetableView();
		updateTimeTableView();
	});


	function captureTT(isColor){

		if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
		{
			$('html').css("max-width","900px");
		}
		{
			window.bidit_globals.g_printRes = $(window).width();
			$('html').width(900);
		}
		$('#examsForPrint').css("max-height","");

		$('#timeTable').removeClass('table-striped');

		/*in case of IE add the borders of the table*/
		if (!(/msie/.test(navigator.userAgent.toLowerCase()))){
			//$('#timeTable').attr('border','1');
		}

		$('#ttHead').removeClass('info');
		colorHeaders();

		$('.navbar').addClass('hide');
		$('.tabbable').addClass('hide');
		$('#accordionParentDiv').addClass('hide');
		$('#search').addClass('hide');
		$('#optimizeButtons').addClass('hide');
		$('#hoursDiv').addClass('hide');
		$('#chooseCoursesBlueBtn').addClass('hide');
		$('#rightFooterAreatStrip').addClass('hide');
		/**/

		$('#examsHeader').addClass('hide');
		//$('#examsHeaderWhite').addClass('hide');
		$('#ExclamationDiv').addClass('hide');
		$('#examsForPrint').addClass('hide');
		$('#lowerWide').css("max-width","900px");

		/**/
		$('#calendarStrip').addClass('hide');
		$('#footerAreaPrinting').addClass('hide');		
		$('#alertsArea').css("display","none");

		$('#backFromPrint').removeClass('hide');
		$('#mailPrint').removeClass('hide');
		$('#printPrint').removeClass('hide');

		$('#html2canvasArea').empty();



		$('#backFromPrint').addClass('hide');
		$('#mailPrint').addClass('hide');
		$('#printPrint').addClass('hide');
		$('#goToPrint').addClass('hide');


		enlargeTT();
		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();

		/*format the colors and the borders of the printed TT. parameter is true if coor and false for white*/
		whiteTT(isColor);

		//
		for (var i=1 ; i<$('.ttClass').length + 1 ; i++){
			$('.ttClass:nth-child('+i+')').text(function(){
				//save the old one in global
				return removeBraces($('.ttClass:nth-child('+i+')').text());

			});

		}

		canvasFunc();



	}

	function restoreTT(){
		$('html').width(window.bidit_globals.g_printRes);
		if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
		{
			$('html').css("max-width","");
		}
		$('#examsForPrint').css("max-height","233px");
		restoreBullets();
		$('#timeTable').addClass('table-striped');	
		$('#ttHead').addClass('info');
		uncolorHeaders();
		$('#tableRF').removeClass('hide');
		$('.navbar').removeClass('hide');
		$('.tabbable').removeClass('hide');
		$('#accordionParentDiv').removeClass('hide');
		$('#search').removeClass('hide');
		$('#optimizeButtons').removeClass('hide');
		$('#hoursDiv').removeClass('hide');
		$('#chooseCoursesBlueBtn').removeClass('hide');
		$('#rightFooterAreatStrip').removeClass('hide');
		$('#examsHeader').removeClass('hide');
		$('#examsHeaderWhite').addClass('hide');
		$('#ExclamationDiv').removeClass('hide');
		$('#examsForPrint').removeClass('hide');
		$('#lowerWide').css("max-width","");
		$('#calendarStrip').removeClass('hide');
		$('#footerAreaPrinting').removeClass('hide');


		$('#alertsArea').css("display","block");

		$('#backFromPrint').addClass('hide');
		$('#mailPrint').addClass('hide');
		$('#printPrint').addClass('hide');

		$('#html2canvasArea').addClass('hide');



		$('#detailsForPrint').css("display","none");
		$('#detailsForPrint').addClass('hide');
		//$('#detailsForPrint').empty();

		window.bidit_globals.g_printOnlyCurrSem = false;
		updateExamsAndCalendar();
		diminishTT();
		restoreWhiteTT();
		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();


	}

	function canvasFunc(){
		if(jQuery.browser.name.toLowerCase() == 'firefox'){
			html2canvas(document.body, {
				onrendered: function(canvas) {
					canvasFuncHelper(canvas);
				},
				letterRendering: true,
				height: 750,
				width: 880,
			});	
		}
		else {
			html2canvas(document.body, {
				onrendered: function(canvas) {
					canvasFuncHelper(canvas);
				},
				letterRendering: true,
				height: 750,
			});	
		}
	}
	

	
	$('#printFromPrint').click(function(){
		window.print();
		restoreTT();
		$('#goToPrint').removeClass('hide');
	});
	
	$('#goBackFromPrint').click(function(){
		restoreTT();
		$('#goToPrint').removeClass('hide');
	});
	
	

	
	function canvasFuncHelper(canvas,firefoxBool){

		document.getElementById('html2canvasArea').appendChild(canvas);
		//  $('#html2canvasArea').append(canvas);
		//document.body.appendChild(canvas);
		//$('#html2canvasArea').css("margin-bottom","-200px");
		$('#html2canvasArea').removeClass('hide');
		$('#examsHeader').addClass('hide');
		$('#examsHeaderWhite').removeClass('hide');
		/**/
		//$('#ExclamationDiv').removeClass('hide');
		$('#examsForPrint').removeClass('hide');
		$('#examsForPrint').css("max-height","20000px");
		window.bidit_globals.g_printOnlyCurrSem = true;
		updateExamsAndCalendar();
		/**/
		$('#tableRF').addClass('hide');

		$('#backFromPrint').removeClass('hide');
		$('#mailPrint').removeClass('hide');
		$('#printPrint').removeClass('hide');
		$('#detailsForPrint').removeClass('hide');
		$('#detailsForPrint').css("display","inline-block");
		
		changePrintButtonsLocation();
		/*
		$('#detailsForPrint').empty();
		$('#detailsForPrint').append(function(){
			return '<img src="assets/img/logo-black.jpg"  />'+
			'<button id="goBackFromPrint" class="btn btn-info btn-medium noPrint">חזרה</button>';
		});
		*/
		

		hideBullets();

	}

	$('#goToPrintColor').click(function(){
		captureTT(true);
	});

	$('#goToPrintWhite').click(function(){
		captureTT(false);
	});

	/*
	$('#backFromPrint').click(function(){
		$('#backFromPrint').addClass('hide');
		$('#goToPrint').removeClass('hide');
		restoreTT();	

	});
	 */

	function calcHeight(){
		return 1000;	

	}
	/*
	$('#mailPrint').click(function(){


	});

	$('#printPrint').click(function(){
		window.print();
	});
	 */
	function hideBullets(){
		$(".bulletSym").addClass('hide');
	}

	function restoreBullets(){
		$(".bulletSym").removeClass('hide');
	}

	function whiteTT(isColor){
		//return;
		/*switch classes for no color*/

		/*in case its IE and fixing the problem with borders*/
		/*
		if((jQuery.browser.name.toLowerCase() == 'microsoft internet explorer') || true ||
		(navigator.userAgent.toLowerCase().indexOf('msie') > -1)){}
		 */


		//$('.ttClass').css("background-color","white");
		$('.ttClass').css('border','2px solid black');
		$('#timeTable > tbody > tr > td').css('border','2px solid #BDBDBD','!important');
		//$('.ttClass').css("margin-top","0px","!important");
		//$('.ttClass').css("margin-left","-3px","!important");
		var oldWidth;
		var newWidth;
		var oldHeight;
		var newHeight;

		$('.ttClass').each(function(tc){

			oldWidth = $(this).width();
			newWidth = oldWidth * 0.98;
			$(this).width(newWidth);

			oldHeight = $(this).height();
			newHeight = oldHeight * 0.98;
			$(this).height(newHeight);


			$(this).css("margin-top","-2px","!important");
		});




		if (isColor == false){
			$('.ttClass').css("background-color","white");
			$('.ttClass').css("color","black");
			$('.ttClass').css("opacity","1");
			$('.ttClass').css("filter","");

			$('.ttClassColor').css("background-color","white");
			$('.ttClassColor').css("color","black");
			$('.ttClassColor').css("opacity","1");
			$('.ttClassColor').css("filter","");
		}
	}

	function restoreWhiteTT(){
		/*switch classes for no color*/

		$('.ttClass').css("background-color","");
		$('.ttClass').css("color","");
		$('.ttClass').css("opacity","0.8");
		$('.ttClass').css("filter","alpha(opacity =       80)");

		$('.ttClassColor').css("background-color","");
		$('.ttClassColor').css("color","");
		$('.ttClassColor').css("opacity","0.8");
		$('.ttClassColor').css("filter","alpha(opacity =       80)");	
		//$('#timeTable').attr('border','');
		/*
		if((jQuery.browser.name.toLowerCase() == 'microsoft internet explorer') ||
		(navigator.userAgent.toLowerCase().indexOf('msie') > -1)){
		$('#timeTable > tbody > tr > td').css('border','');
		}
		 */
		$('#timeTable > tbody > tr > td').css('border','');

		// Updating group selections on schedule
		clearTimetableView();
		updateTimeTableView();
	}

	function enlargeTT(){
		$('#timeTable > tbody > tr').css("height","45px");
		$('#timeTable').css("width","900px");
		$('#timeTable').css("margin-right","-192px");
	}

	function diminishTT(){
		$('#timeTable > tbody > tr').css("height","");
		$('#timeTable').css("width","");
		$('#timeTable').css("margin-right","");
	}

	function colorHeaders(){
		var backCol = "#EEE";
		$('#ttHead').css("background-color",backCol);
		$('#hour08').css("background-color",backCol);
		$('#hour09').css("background-color",backCol);
		$('#hour10').css("background-color",backCol);
		$('#hour11').css("background-color",backCol);
		$('#hour12').css("background-color",backCol);
		$('#hour13').css("background-color",backCol);
		$('#hour14').css("background-color",backCol);
		$('#hour15').css("background-color",backCol);
		$('#hour16').css("background-color",backCol);
		$('#hour17').css("background-color",backCol);
		$('#hour18').css("background-color",backCol);
		$('#hour19').css("background-color",backCol);
		$('#hour20').css("background-color",backCol);
		$('#hour21').css("background-color",backCol);
	}

	function uncolorHeaders(){
		$('#ttHead').css("background-color","");
		$('#hour08').css("background-color","");
		$('#hour09').css("background-color","");
		$('#hour10').css("background-color","");
		$('#hour11').css("background-color","");
		$('#hour12').css("background-color","");
		$('#hour13').css("background-color","");
		$('#hour14').css("background-color","");
		$('#hour15').css("background-color","");
		$('#hour16').css("background-color","");
		$('#hour17').css("background-color","");
		$('#hour18').css("background-color","");
		$('#hour19').css("background-color","");
		$('#hour20').css("background-color","");
		$('#hour21').css("background-color","");
	}

	function removeBraces(input){
		//check for IE7

		if(/msie/.test(navigator.userAgent.toLowerCase())){
			//return input;
		}
		//else

		var first = -1;
		var last = -1;
		for (var i=input.length-1 ; i>0 ; i--){
			if (input[i]==")" || input[i]=="("){
				if (last == -1) {
					last=i;
					continue;
				}
				if (first == -1){
					first=i;
					continue;
				}
			}
		}
		if (first>-1 && last>-1) {
			var retStr = '';
			retStr += input.substring(0,first);
			retStr += '\n)';
			retStr += input.substring(first+1,last);
			retStr += input.substring(last+1,input.length);
			retStr += '(';
			return retStr;

		}
		return input;
	}
	
	function changePrintButtonsLocation(){
		var currWidth = $(window).width();

		if (currWidth > 900)
		{
			$('#printButtonsInPrint').css('right','796px');
			$('#printButtonsInPrint').css('left','');
		}
		
		else {
			$('#printButtonsInPrint').css('right','');
			$('#printButtonsInPrint').css('left','2%');
		}

	}

	/*================================================================================================
	 *                             Courses Popularity (Course Profile Screen)
	 *================================================================================================
	 */

	$('#popularityMainDiv').delegate('#loginFromPopularity','click',function(){
		localStorage.courseProfileFacebook = window.bidit_globals.g_currCourseProfile;
		operateLogging();

	});

	$('#popularityTab').click(function(){
		var hasClassDis = $(this).hasClass('facebookTabBtnDisabled');
		if(hasClassDis == false){
			$('#popularityTab').addClass('facebookTabBtnDisabled');
			updatePopularityTab(true);
		}

	});

	$('body').delegate('li[id^="friendCourse"]','mouseenter',function(){
		$(this).unbind('click');
		$(this).on('click', function(){
			$('#courseProfileModal').modal('hide');
			window.bidit_globals.g_currCourseProfile = ($(this).attr('id')).substring(12);
			window.bidit_globals.g_currChosenInfoBtnDepart = window.bidit_globals.g_currCourseProfile.substring(0,4);
			window.bidit_globals.g_isProfileOpenedFromMain = true;

			$('#tab3x').empty();
			abortAllSyllabusRequests();
			syllabusRequestAjax = $.ajax({
				type: "GET",
				url: "/ajax/get-syllabus/",
				dataType: 'json', 
				data: { 'university': window.bidit_globals.g_currUniversity,
					'semester': (window.bidit_globals.g_currSemester+1),
					'course_num': window.bidit_globals.g_currCourseProfile },
					success: function(data)
					{
						syllabusRequestAjax = null;
						showCourseSyllabus(data);
					}
			});//ajax closed


			$.when(getCurrentCourseFromAjax()).done(function(a6, textStatus, jqXHR){
				courseProfileInit();
				window.setTimeout(unAssignCourseProfileData,1000);
				window.setTimeout(function(){
					checkIfCanAssignProfileData(a6);
				},1000);
				window.setTimeout(function(){
					$('#courseProfileModal').modal('show');
				},1002);
			});
		});
	});


	/*if there are courses show the optimizer button , moved here because needs the all page loads for the print*/
	showOrHideOptimizeButton();

	/****************end of main function******************/
});

